jQuery UI 1.6 The User Interface Library for jQuery phần 2 ppt

43 451 0
jQuery UI 1.6 The User Interface Library for jQuery phần 2 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Tabs Configurable properties An object can be passed to the tabs() constructor method to configure different properties of the tabbed interface The following table provides the available properties to configure non-default behaviours when using the tabs widget: Property ajaxOptions Default Value {} Usage cache "false" Load remote tab content only once (lazy-load) cookie null Show active tab using cookie data on page load disabled [] Disable specified tabs on pageload idPrefix "ui-tabs-" Used when a remote tab's link element has no title attribute event "click" Tabs event that triggers display of content fx null Specify a transition effect when changing tabs panelTemplate A string specifying the elements used for the content section of a dynamically created tab selected The tab selected by default when the widget renders spinner "Loading&#B230" Specify the loading spinner for remote tabs tabTemplate
  • #{label}
  • false A string specifying the elements used when creating new tabs dynamically unselect Options for remote AJAX tabs Hides an already selected tab when it is clicked In addition to these properties, default values for all of the class names for the different elements and states of the tab widget are also defined: Property disabledCLass hideClass loadingClass navClass panelClass selectedClass unselectClass Default Value "ui-tabs-disabled" "ui-tabs-hide" "ui-tabs-loading" "ui-tabs-nav" "ui-tabs-panel" "ui-tabs-selected" "ui-tabs-unselect" [ 28 ] Chapter We targeted some of these properties when we wrote our custom stylesheet in the previous example These properties make the widget more flexible in the class names that are automatically applied to different elements within it Let's look at how these configurable properties can be used For example, if we wanted to configure the tabs to initially display the second content panel when the widget is rendered, we could use the following code: jQuery UI Tabs Example 3
    • Tab 1
    • Tab 2
    This is the content panel linked to the first tab, it is shown by default. This content is linked to the second tab and will be shown when its tab is clicked. //define function to be executed on document ready $(function(){ //define config object var tabOpts = { selected: }; //create the tabs $("#myTabs").tabs(tabOpts); }); [ 29 ] Tabs Save this as tabs3.html in your jqueryui folder The different tabs, and their associated content panels, are represented by a numerical index starting at zero, much like a standard JavaScript array Specifying a different tab to open by default is as easy as supplying its index number as the value for the selected property You can also specify that no tabs should open initially by supplying null as the value for this property You may want a particular tab to be disabled until a certain condition is met This is easily achieved by manipulating the disabled property of the tabs This property is an empty array by default, but you can disable a tab just by adding its index as an item in this array Change tabs3.html to this: jQuery UI Tabs Example 4
    • Tab 1
    • Tab 2
    This is the content panel linked to the first tab, it is shown by default. This content is linked to the second tab and will be shown when its tab is clicked. //define function to be executed on document ready $(function(){ //define config object var tabOpts = { selected: 1, disabled: [0] [ 30 ] Chapter }; //create the tabs $("#myTabs").tabs(tabOpts); }); Save this as tabs4.html in your jqueryui folder In this example, we added the index of the first tab to the disabled array We could add the indices of other tabs to this array as well, separated by a comma, to disable multiple tabs by default When the page is loaded in a browser, the first tab will be permanently styled in the hover state and will not respond to mouse overs or clicks at all as seen in this example: Transition effects We can easily add attractive transition effects, which are displayed when tabs open and close, using the fx property This property is configured using another object literal, or an array, inside our configuration object which enables one or more effects Let's enable fading effects using the following code: jQuery UI Tabs Example 5 [ 31 ] Tabs
    • Tab 1
    • Tab 2
    This is the content panel linked to the first tab, it is shown by default. This content is linked to the second tab and will be shown when its tab is clicked. //define function to be executed on document ready $(function(){ //define config object var tabOpts = { fx: { opacity: "toggle", duration: "slow" } }; //create the tabs $("#myTabs").tabs(tabOpts); }); Save this file as tabs5.html in your jqueryui folder The fx object we created has two properties The first property is the animation To use fading, we specify opacity as this is what is adjusted, to use opening animations we would specify height as the property name Toggling the opacity simply reverses its current setting If it is currently visible, it is made invisible, and vice-versa The second property, duration, specifies the speed at which the animation occurs The values for this property are slow, normal, or fast, with normal being the default As we can see, when we run the file, the tab content slowly fades out as a tab closes and fades in when a new tab opens Both animations occur during a single tab interaction To only show the animation once, when a tab closes for example, [ 32 ] Chapter we would need to nest the fx object within an array Change the last block in tabs5.html so that it appears as follows: //define function to be executed on document ready $(function(){ //define config object var tabOpts = { fx: [{ opacity: "toggle", duration: "slow" }, null] }; //create the tabs $("#myTabs").tabs(tabOpts); }); The closing effect is contained within an object in the first item of the array, and the opening animation is the second By specifying null as the second item, we effectively turn off opening animations We can also specify different animations and speeds for opening and closing animations by adding another object as the second array item if we wish instead of null Save this as tabs6.html and view the results in your browser Tab events The tab widget defines a series of useful properties that allow you to add callback functions to easily perform different actions when certain events exposed by the widget are detected The following table lists the configuration properties that are able to accept executable functions on an event: Property add Usage disable Execute a function when a tab is disabled enable Execute a function when a tab is enabled load Execute a function when a tab's remote data has loaded remove Execute a function when a tab is removed select Execute a function when a tab is selected show Execute a function when the content section of a tab is shown Execute a function when a new tab is added [ 33 ] Tabs Each component of the library has callback properties, such as those in the previous table, which are tuned to look for key moments in any visitor interaction These properties make it very easy to add code that reacts to different situations Any functions we use with these callbacks are usually executed before the change happens Therefore, you can return false from your callback and prevent the action from occurring The previous technique is the standard means of working with events in the jQuery UI world There is also a less common way that may become necessary in certain situations We can also use the standard jQuery bind() method to bind an event handler to a custom event fired by the tabs widget in the same way that we could bind to a standard DOM event, such as a click The reason this is possible is that apart from internally invoking any callback function specified in one of the properties listed above, custom events are also fired when different things occur The following table lists the tab's custom binding events and their triggers: Event tabsselect Trigger tabsload A remote tab has loaded tabsshow A tab is shown tabsadd A tab has been added to the interface tabsremove A tab has been removed from the interface tabsdisable A tab has been disabled tabsenable A tab has been enabled A tab is selected The first three events are fired in succession in the order in which they appear in the table If no tabs are remote, tabsselect and tabsshow are fired in that order These events are all fired after the action has occurred So, the tabsadd event will fire after the new tab has been added In our next example, we can look at how easy it is to react to a particular tab being selected using the standard non-bind technique Change the tabs6.html file so that it appears as follows: [ 34 ] Chapter jQuery UI Tabs Example 7
    • Tab 1
    • Tab 2
    This is the content panel linked to the first tab, it is shown by default. This content is linked to the second tab and will be shown when its tab is clicked. //define function to be executed on document ready $(function(){ //alert the id of the tab that was selected function handleSelect(event, tab) { alert("The tab at index " + tab.index + " was selected"); } //define config object var tabOpts = { select:handleSelect }; //create the tabs $("#myTabs").tabs(tabOpts); }); Save this file as tabs7.html in your jqueryui folder We made use of the select callback in this example, although the principal is the same for any of the other custom events fired by tabs The name of our callback function is provided as the value of the select property in our configuration object [ 35 ] Tabs Two arguments will automatically be passed to the function we define by the widget when it is executed These are the original event object, and a custom object containing useful properties from the tab which is in the function's scope Scope can be a tricky subject, and I'm assuming here that you already have some knowledge of scope in JavaScript If you don't, the simple explanation for this example is that whichever tab is clicked will be in the scope chain in the context of our callback function To tell which of the tabs was clicked, we can look at the index property of the second object (remember these are zero-based indices) This is added, along with a little explanatory text, to a standard JavaScript alert In this example, the callback function was defined outside of the configuration object, and was instead referenced by the object We can also define these callback functions inside of our configuration object to make our code more efficient For example, our function and configuration object from the previous example could have been defined like this: var tabOpts = { add: function(event, tab) { alert("The tab at index " + tab.index + " was selected"); } } See tabs7inline.html in the code download for this chapter for further clarification on this way of using event callbacks Whenever a tab is selected, you should see the alert before the change occurs as seen below: [ 36 ] Chapter Using tab methods The tabs widget contains many different methods, which means it has a rich set of behaviours and also supports the implementation of advanced functionality that allows us to work with it programmatically Let's take a look at these methods which are listed in the following table: Method Usage add Add a new tab programmatically, specifying the URL of the tab's content, a label, and optionally its index number as arguments remove Remove a tab programmatically, specifying the index of the tab to remove enable Enable a disabled tab based on index number disable Disable a tab based on index number select Select a tab programmatically, which has the same effect as when a visitor clicks a tab, based on index number load Reload an AJAX tab's content, specifying the index number of the tab url Change the URL of content given to an AJAX tab; the method expects the index number of the tab and the new URL destroy Completely remove the tabs widget length Return the number of tabs in the widget rotate Automatically changes the active tab after a specified number of milliseconds have passed either once or repeatedly I mentioned jQuery UI's simplified API in Chapter 1, and in the next few examples, we'll get to see just how simple using it is Enabling and disabling tabs We can make use of the enable or disable methods to programmatically enable or disable specific tabs This will effectively switch on any tabs that were initially disabled Let's use the enable method to switch on the first tab, which we disabled by default in an earlier example Change the tabs4.html file as follows: [ 37 ] Tabs Summary The tabs widget is an excellent way of saving space on your page by organizing related, or even completely unrelated) sections of content that can be shown, or hidden, with simple click-input from your visitors It also lends an air of interactivity to your site that can help improve the overall functionality and appeal of the page on which it is used Let's review what was covered in this chapter We first looked at how, with just a little underlying HTML and a single line of jQuery-flavoured JavaScript code, we can implement that default tabs widget We then saw how easy it is to add our very own basic styling for the tabs widget so that its appearance, but not its behaviour, is completely altered We already know that in addition to this there are two stylesheets from jQuery UI we can use (flora and default), or that we can create a completely new theme using Theme Roller We then moved on to look at the set of configurable properties exposed by the tabs API With these, we can enable or disable different options that the widget supports, such as whether tabs are selected by clicks or another event, whether certain tabs are disabled when the widget is rendered, etc We took some time to look at how we can use a range of predefined callback properties that allow us to execute arbitrary code when different events are detected We also saw that the jQuery bind() method can listen for the same events if it becomes necessary Following the configurable properties, we looked at the range of methods that we can use to programmatically make the tabs perform different actions, such as simulating a click on a tab, enabling or disabling a tab, and adding or removing tabs We briefly looked at some of the more advanced functionality supported by the tabs widget such as AJAX tabs and the tab carousel Both of these techniques are incredibly easy to use and can add value to any implementation [ 56 ] The Accordion Widget The accordion widget is another UI widget made up of a series of containers for your content, all of which are closed except for one Therefore, most of its content is initially hidden from view, much like the tabs widget that we looked at in the previous chapter Each container has a heading element associated with it, which is used to open the container and display the content When you click on a heading, its content is displayed When you click on another heading, the currently visible content is hidden while the new content is shown The accordion widget is a robust and highly configurable widget that allows you to save space on your web pages by only displaying a certain section of related content at any one time This is like a tabbed interface but positioned vertically instead of horizontally It's easy for your visitors to use and it's easy for us to implement It has a range of configurable properties that can be used to customize its appearance and behaviour It also has a series of methods that allow you to control it programmatically You should note that the height of the accordion's container element will automatically be set so that there is room to show the tallest content panel in addition to the headers This will vary, of course, depending on the width that you set on the widget's container In this chapter, we are going to cover the following topics: • • • • • • • The structure of an accordion widget A default implementation of an accordion Adding custom styling The configurable properties Built-in methods for working with the accordion Built-in types of animation Custom accordion events The Accordion Widget Accordion's structure Let's take a moment to familiarize ourselves with what an accordion is made of Within the outer container is a series of links These links are the headings within the accordion and each heading will have a corresponding content panel, or drawer as they are sometimes referred to, which opens when the heading is clicked The following screenshot shows these elements as they may appear in an accordion: It's worth remembering that when using the accordion widget, only one content panel can be open at any one time Let's implement a basic accordion now In a blank page in your text editor, create the following page: jQuery UI Accordion Widget Example 1
    • Header 1 Wow, look at all this content that can be shown or hidden with a simple click!
    • Header 2 Lorem ipsum dolor sit amet, consectetuer adipiscing elit Aenean sollicitudin Sed interdum pulvinar justo Nam iaculis volutpat ligula Integer vitae felis quis diam laoreet ullamcorper Etiam tincidunt est vitae est Ut posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus Suspendisse potenti [ 58 ] Chapter
    • Header 3 Donec at dolor ac metus pharetra aliquam Suspendisse purus Fusce tempor ultrices libero Sed quis nunc Pellentesque tincidunt viverra felis Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus.
    //function to execute when doc ready $(function() { //turn specified element into an accordion $("#myAccordion").accordion(); }); Save the file as accordion1.html in your jqueryui folder and try it out in a browser We haven't specified any styling at all at this stage, but as you can see from the following screenshot, it still functions exactly as intended: [ 59 ] The Accordion Widget Little code is required for a basic working version of the accordion widget A simple unordered list element is the mark-up foundation which is transformed by the library into the accordion object The following three separate external script files are required for an accordion: • The jQuery library itself (jquery-1.2.6.js) • The UI base file (ui.core.js) • The accordion source file (ui.accordion.js) The first two files are mandatory requirements of all components of the UI library They should be linked to in the order shown here Each widget also has its own source file, and may depend on other components as well The order in which these files appear is important The jQuery library must always appear first, followed by the UI base file After these files, any other files that the widget depends upon should appear before the widget's own script file The library components will not function as expected if files are not loaded in the correct order Finally, we use a custom block to turn our
      element into the accordion We can use the jQuery object shortcut $ to specify an anonymous function which will be executed as soon as the document is ready This is analogous to using $(document).ready(function(){}) and helps to cut down on the amount of code we have to type Following this, we use the simple ID selector $("#myAccordion") to specify the element on the page we want to transform We then use the accordion() constructor method to create the accordion Other elements can be turned into accordions as well All list element variants are supported including ordered lists and definition lists You don't even need to base the accordion on a list element at all You can build a perfectly functional accordion using just nested and elements, although additional configuration will be required In this example, we used an empty fragment (#) as the value of the href attribute You should note that any URLs supplied for accordion headers will not be followed when the header is clicked within the accordion when using the default implementation [ 60 ] Chapter Styling the accordion With no styling, the accordion will take up 100% of the width of its container Like with other widgets, we have several options for styling the accordion We can create our own custom stylesheet to control the appearance of the accordion and its content, we can use the default or flora themes that come with the library, or we can use Theme Roller to create an extensive skin for the whole library Let's see how using the flora theme for the accordion will cause it to render In accordion1.html, add the following tag to the of the page: Save the new file as accordion2.html, also in the jqueryui folder, and view it again in a browser It should appear something like this: The accordion theme file assumes that an unordered list is being used as the basis of the widget and specifically targets
    • elements with certain style rules We can easily create our own custom theme to style the accordion for situations where we want to use a non list-based accordion widget, or if we simply want different colors or font styles You can use the excellent Firebug plugin for Firefox, or another DOM viewer, to see the class names that are automatically added to certain elements when the accordion is generated You can also read through an un-minified version of the source file if you really feel like it These will be the class names that we'll be targeting with our custom CSS [ 61 ] The Accordion Widget The following screenshot shows Firebug in action: Change accordion2.html so that it appears as follows (new code is shown in bold): jQuery UI Accordion Widget Example 3 Header 1Wow, look at all this content that can be shown or hidden with a simple click! Header 2Lorem ipsum [ 62 ] Chapter Header 3Donec at dolor ac metus pharetra aliquam Suspendisse purus Fusce tempor ultrices libero Sed quis nunc Pellentesque tincidunt viverra felis Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus. //function to execute when doc ready $(function() { //turn specified element into an accordion $("#myAccordion").accordion(); }); Save this version as accordion3.html in the jqueryui folder The class name ui-accordion is automatically added to the accordion's container element Therefore, we can use this as a starting point for most of our CSS selectors The links that form our drawer headers are given the class ui-accordion-header so we can also target this class name In a new file, create the following stylesheet: #myAccordion { width:200px; border:2px solid #000000; position:relative; list-style-type:none; padding-left:0; } ui-accordion-header { text-decoration:none; font-weight:bold; color:#000000; display:block; width:100%; text-align:center; } ui-accordion div div { font-size:90%; } [ 63 ] The Accordion Widget ui-accordion a { color:#ffffff; background:url( /img/accordion/header-sprite.gif) repeat-x 0px 0px; } ui-accordion a.selected { background:url( /img/accordion/header-sprite.gif) repeat-x 0px -22px; } ui-accordion a:hover { background:url( /img/accordion/header-sprite.gif) repeat-x 0px -44px; } /* container rounded corners */ corner { position:absolute; width:12px; height:13px; background:url( /img/accordion/corner-sprite.gif) no-repeat; } topLeft { top:-2px; left:-2px; background-position:0px 0px; } topRight { top:-2px; right:-2px; background-position:0px -13px; } bottomRight { bottom:-2px; right:-2px; background-position:0px -26px; } bottomLeft { bottom:-2px; left:-2px; background-position:0px -39px; } Save this file as accordionTheme.css in your styles folder and preview accordion3.html in a browser We will need a new folder for the images we use in this and subsequent examples Create a new folder inside the img folder and name it accordion With just two images, and a few simple style rules, we can drastically change the default appearance of the accordion with our own custom skin as shown in the following screenshot: [ 64 ] Chapter Configuring accordion The accordion has a range of configurable properties which allow us to easily change the default behaviour of the widget The following table lists the available properties, their default value, and gives a brief description of their usage: Property Default Value Usage active Selector for the initially open drawer alwaysOpen first child true animated "slide" Animate the opening of drawers autoHeight true Automatically set height according to the biggest drawer clearStyle false Clear styles after an animation event "click" Event on headers that trigger drawers to open fillSpace false Accordion completely fills height of its container header "a" Selector for header elements navigation false Enable navigation for accordion navigationFilter location.href By default, this property opens the drawer whose heading's href matches location.href selectedClass "selected" Class name applied to headers with open drawers Ensure that one drawer is open at all times [ 65 ] The Accordion Widget Configurable properties The configurable properties for all of the different components of jQuery UI are constantly evolving with each new release of the library You can keep track of the latest properties by looking through the online jQuery UI API pages Each component has its own page and can be accessed from http://docs.jquery.com/UI/ Most of the properties are self-explanatory, and the values they accept are usually booleans, strings, or element references Let's put some of them to use so we can explore their functionality Alter accordion3.html so that it appears as follows:� jQuery UI Accordion Widget Example 4 Header 1Wow, look at all this content that can be shown or hidden with a simple mouseover! Header 2Lorem ipsum dolor sit amet, consectetuer adipiscing elit Aenean sollicitudin Sed interdum pulvinar justo Nam iaculis volutpat ligula Integer vitae felis quis diam laoreet ullamcorper Etiam tincidunt est vitae est Ut posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus Suspendisse potenti. Header 3Donec at dolor ac metus pharetra aliquam Suspendisse purus Fusce tempor ultrices libero Sed quis nunc Pellentesque tincidunt viverra felis Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus. [ 66 ] Chapter //function to execute when doc ready $(function() { //set the event property var accOpts = { event:"mouseover" } //turn specified element into an accordion $("#myAccordion").accordion(accOpts); }); First, we create a new object literal called accOpts which contains one property key and a value We then pass this object into the accordion() constructor as an argument, and it overrides the default properties of the widget The string we specified for the value of the event property becomes the event that triggers the activation of the drawers, making this a very useful property Save the changes as accordion4.html You should note that you can also set properties using an inline object within the widget's constructor method without creating a separate object (see accordion4Inline.html) Using the following code would be equally as effective, and would often be the preferred way for coding: //function to execute when doc ready $(function() { //turn specified element into an accordion $("#myAccordion").accordion({ event:"mouseover" }); }); [ 67 ] The Accordion Widget We can set other properties at the same time as well If we want to change which drawer is open by default when the accordion is rendered, as well as change the trigger event, we would supply both properties and the required values, with each pair separated by a comma Update accordion4.html so that it appears as follows: jQuery UI Accordion Widget Example 5 Header 1Wow, look at all this content that can be shown or hidden with a simple mouseover! Header 2Lorem ipsum dolor sit amet, consectetuer adipiscing elit Aenean sollicitudin Sed interdum pulvinar justo Nam iaculis volutpat ligula Integer vitae felis quis diam laoreet ullamcorper Etiam tincidunt est vitae est Ut posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus Suspendisse potenti. Header 3Donec at dolor ac metus pharetra aliquam Suspendisse purus Fusce tempor ultrices libero Sed quis nunc Pellentesque tincidunt viverra felis Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus //function to execute when doc ready $(function() { //configure accordion [ 68 ] Chapter var accOpts = { event:"mouseover", active:"#header3" } //turn specified element into an accordion $("#myAccordion").accordion(accOpts); }); The first change is to give our header elements id attributes in the underlying HTML in order to target them with the active property In our object literal, we then specify the selector for the header we would like to open by default Save the file as accordion5.html When the page is opened, the third drawer should be displayed by default The other properties listed in the table at the start of this section are equally as easy to configure Change the object literal so that it appears as follows: //configure accordion var accOpts = { event:"mouseover", active:"#header3", alwaysOpen:false, autoHeight:false } Save these changes as accordion6.html and view the results in a browser First, you should find that when you first roll over a heading the drawer opens as normal, but the accordion grows or shrinks depending on how much content is in the drawer It no longer stays at a fixed height This can be seen in the following example: [ 69 ] The Accordion Widget You should also find that if you roll over a heading whose drawer is already open, the drawer will close and the accordion will shrink so that only the headers are displayed with no open drawers Note that when using false with the alwaysOpen property, the accordion will shrink in this way regardless of whether the autoHeight property is set to true or false The fillSpace property, if set, will override autoHeight You should also be aware that the clearStyle property will not work with autoHeight One final property we should look at is the navigation property This property is used to enable navigating to new pages from accordion headings Change accordion6.html to this: jQuery UI Accordion Widget Example 7 Header 1Wow, look at all this content that can be shown or hidden with a simple mouseover! Header 2Lorem ipsum dolor sit amet, consectetuer adipiscing elit Aenean sollicitudin Sed interdum pulvinar justo Nam iaculis volutpat ligula Integer vitae felis quis diam laoreet ullamcorper Etiam tincidunt est vitae est Ut [ 70 ] ... type="text/javascript" src="jqueryui1.6rc2/ jquery- 1 .2. 6.js"> ... type="text/javascript" src="jqueryui1.6rc2/ jquery- 1 .2. 6.js"> ... type="text/javascript" src="jqueryui1.6rc2/ jquery- 1 .2. 6.js">

    Ngày đăng: 12/08/2014, 19:21

    Từ khóa liên quan

    Mục lục

    • Chapter 2: Tabs

      • Configurable properties

      • Transition effects

      • Tab events

      • Using tab methods

        • Enabling and disabling tabs

        • Adding and removing tabs

        • Simulating clicks

        • Creating a tab carousel

        • AJAX tabs

        • Fun with tabs

        • Summary

        • Chapter 3: The Accordion Widget

          • Accordion's structure

          • Styling the accordion

          • Configuring accordion

    Tài liệu cùng người dùng

    Tài liệu liên quan