SlideShare une entreprise Scribd logo
1  sur  12
Télécharger pour lire hors ligne
1.   How to Create A Nested Filter:
            view plain   copy to clipboard   print   ?

      01.   //a filter allows you to reduce the set of matched elements
      02.   //to those that match a given selector. In this case the query
      03.   //removes anything which doesn't (:not) have (:has) a child with
      04.   //class "selected" (.selected)
      05.
      06.   .filter(":not(:has(.selected))")


2.   How to Reuse Your Element Searches
            view plain   copy to clipboard   print   ?

      01.   var allItems = $("div.item");
      02.   var keepList = $("div#container1 div.item");
      03.
      04.   //Now you can keep working with those jQuery objects. For example,
      05.   //trim down the "keep list" based on checkboxes whose names
      06.   //correspond to <div> class names:
      07.
      08.   $(formToLookAt + " input:checked").each(function() {
      09.       keepListkeepList = keepList.filter("." + $(this).attr("name"));
      10.   });
      11.   </div>


3.   How To Check If An Element contains a certain class or
     element with has():
            view plain   copy to clipboard   print   ?

      01.   //jQuery 1.4.* includes support for the has method. This method will find
      02.   //if a an element contains a certain other element class or whatever it is
      03.   //you are looking for and do anything you want to them.
      04.
      05.   $("input").has(".email").addClass("email_icon");




4.   How to Switch StyleSheets With jQuery:
view plain   copy to clipboard   print   ?

       01.   //Look for the media‐type you wish to switch then set the href to your new style sheet
       02.   $('link[media='screen']').attr('href', 'Alternative.css');


 5.   How to Limit the Scope of Selection (For
      Optimization):
             view plain   copy to clipboard   print   ?

       01.   //Where possible, pre‐fix your class names with a tag name
       02.   //so that jQuery doesn't have to spend more time searching
       03.   //for the element you're after. Also remember that anything
       04.   //you can do to be more specific about where the element is
       05.   //on your page will cut down on execution/search times
       06.
       07.   var in_stock = $('#shopping_cart_items input.is_in_stock');

             view plain   copy to clipboard   print   ?

       01.   <ul id="shopping_cart_items">
       02.     <li><input class="is_in_stock" name="item" value="Item‐X" type="radio"> Item X</li>
       03.     <li><input class="3‐5_days" name="item" value="Item‐Y" type="radio"> Item Y</li>
       04.     <li><input class="unknown" name="item" value="Item‐Z" type="radio"> Item Z</li>
       05.   </ul>
       06.


 6.   How to Correctly Use ToggleClass:
             view plain   copy to clipboard   print   ?

       01.   //Toggle class allows you to add or remove a class
       02.   //from an element depending on the presence of that
       03.   //class. Where some developers would use:
       04.
       05.   a.hasClass('blueButton') ? a.removeClass('blueButton') : a.addClass('blueButton');
       06.
       07.   //toggleClass allows you to easily do this using
       08.
       09.   a.toggleClass('blueButton');


 7.   How to set an IE Specific Function:
             view plain   copy to clipboard   print   ?

       01.   if ($.browser.msie) { // Internet Explorer is a sadist. }


 8.   How to Replace an element with jQuery:
             view plain   copy to clipboard   print   ?

       01.   $('#thatdiv').replaceWith('fnuh');


 9.   How to Verify if an element is empty:
             view plain   copy to clipboard   print   ?

       01.   if ($('#keks').html()) { //Nothing found ;}


10.   How to find out the index of an element in an
      unordered set
view plain   copy to clipboard   print   ?

       01.   $("ul > li").click(function () {
       02.       var index = $(this).prevAll().length;
       03.   });


11.   How to Bind a function to an event:
             view plain   copy to clipboard   print   ?

       01.   $('#foo').bind('click', function() {
       02.     alert('User clicked on "foo."');
       03.   });


12.   How to Append or add HTML to an element:
             view plain   copy to clipboard   print   ?

       01.   $('#lal').append('sometext');


13.   How to use an object literal to define properties when
      creating an element
             view plain   copy to clipboard   print   ?

       01.   var e = $("<a>", { href: "#", class: "a‐class another‐class", title: "..." });
       02.   </a>


14.   How to Filter using multiple-attributes
             view plain   copy to clipboard   print   ?

       01.   <a>
       02.         //This precision‐based approached can be useful when you use
       03.         //lots of similar input elements which have different types
       04.         var elements = $('#someid input[type=sometype][value=somevalue]').get();
       05.         </a>


15.   How to Preload images with jQuery:
             view plain   copy to clipboard   print   ?

       01.   <a>
       02.         jQuery.preloadImages = function() { for(var i = 0; i').attr('src', arguments[i]); } };
       03.
       04.         // Usage $.preloadImages('image1.gif', '/path/to/image2.png', 'some/image3.jpg');
       05.         </a>




16.   How to set an event handler for any element that
      matches a selector:
view plain   copy to clipboard   print   ?

       01.   <a>$('button.someClass').live('click', someFunction);
       02.
       03.        //Note that in jQuery 1.4.2, the delegate and undelegate options have been
       04.        //introduced to replace live as they offer better support for context
       05.
       06.        //For example, in terms of a table where before you would use..
       07.
       08.        // .live()
       09.        $("table").each(function(){
       10.          $("td", this).live("hover", function(){
       11.            $(this).toggleClass("hover");
       12.          });
       13.        });
       14.
       15.        //Now use..
       16.
       17.       $("table").delegate("td", "hover", function(){
       18.     $(this).toggleClass("hover");
       19.   });
       20.
       21.        </a>


17.   How to find an option element that's been selected:
             view plain   copy to clipboard   print   ?

       01.   <a> $('#someElement').find('option:selected');
       02.       </a>


18.   How to hide an element that contains text of a certain
      value:
             view plain   copy to clipboard   print   ?

       01.   <a>$("p.value:contains('thetextvalue')").hide();</a>


19.   How To AutoScroll to a section of your page:
             view plain   copy to clipboard   print   ?

       01.   <a>jQuery.fn.autoscroll = function(selector) {
       02.     $('html,body').animate(
       03.       {scrollTop: $(selector).offset().top},
       04.       500
       05.     );
       06.   }
       07.
       08.   //Then to scroll to the class/area you wish to get to like this:
       09.   $('.area_name').autoscroll();
       10.   </a>




20.   How To Detect Any Browser:
             view plain   copy to clipboard   print   ?

       01.   <a> Detect      Safari (if( $.browser.safari)),
       02.       Detect      IE6 and over (if ($.browser.msie && $.browser.version > 6 )),
       03.       Detect      IE6 and below (if ($.browser.msie && $.browser.version <= 6 )),
       04.       Detect      FireFox 2 and above (if ($.browser.mozilla && $.browser.version >= '1.8' ))</a>
21.   How To Replace a word in a string:
             view plain   copy to clipboard   print   ?

       01.   <a>var el = $('#id');
       02.       el.html(el.html().replace(/word/ig, ''));</a>


22.   How To Disable right-click contextual menu :
             view plain   copy to clipboard   print   ?

       01.   <a>$(document).bind('contextmenu',function(e){ return false; });</a>


23.   How to define a Custom Selector
             view plain   copy to clipboard   print   ?

       01.   <a> $.expr[':'].mycustomselector = function(element, index, meta, stack){
       02.       // element‐ is a DOM element
       03.       // index ‐ the current loop index in stack
       04.       // meta ‐ meta data about your selector
       05.       // stack ‐ stack of all elements to loop
       06.
       07.        // Return true to include current element
       08.        // Return false to explude current element
       09.   };
       10.
       11.   // Custom Selector usage:
       12.   $('.someClasses:test').doSomething();
       13.   </a>


24.   How to check if an element exists
             view plain   copy to clipboard   print   ?

       01.   <a>if ($('#someDiv').length) {//hooray!!! it exists...}</a>


25.   How to Detect Both Right & Left Mouse-clicks with
      jQuery:
             view plain   copy to clipboard   print   ?

       01.   <a>$("#someelement").live('click', function(e) {
       02.       if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
       03.           alert("Left Mouse Button Clicked");
       04.       }
       05.       else if(e.button == 2)
       06.           alert("Right Mouse Button Clicked");
       07.   });
       08.
       09.   </a>


26.   How To Show or Erase a Default Value In An Input
      Field:
view plain   copy to clipboard   print   ?

       01.   <a>//This snippet will show you how to keep a default value
       02.   //in a text input field for when a user hasn't entered in
       03.   //a value to replace it
       04.
       05.   swap_val = [];
       06.   $(".swap").each(function(i){
       07.       swap_val[i] = $(this).val();
       08.       $(this).focusin(function(){
       09.           if ($(this).val() == swap_val[i]) {
       10.               $(this).val("");
       11.           }
       12.       }).focusout(function(){
       13.           if ($.trim($(this).val()) == "") {
       14.               $(this).val(swap_val[i]);
       15.           }
       16.       });
       17.   });
       18.   </a>

             view plain   copy to clipboard   print   ?

       01.   <a><input class="swap" value="Enter Username here.." type="text">
       02.   </a>


27.   How To Automatically Hide or Close Elements After An
      Amount Of Time (supports 1.4):
             view plain   copy to clipboard   print   ?

       01.   <a>
       02.    //Here's how we used to do it in 1.3.2 using setTimeout
       03.       setTimeout(function() {
       04.     $('.mydiv').hide('blind', {}, 500)
       05.   }, 5000);
       06.
       07.   //And here's how you can do it with 1.4 using the delay() feature (this is a lot like sleep)
       08.   $(".mydiv").delay(5000).hide('blind', {}, 500);
       09.    </a>


28.   How To Add Dynamically Created Elements to the
      DOM:
             view plain   copy to clipboard   print   ?

       01.   <a> var newDiv = $('');
       02.       newDiv.attr('id','myNewDiv').appendTo('body'); </a>




29.   How To Limit The Number Of Characters in a
      "Text-Area" field:
view plain   copy to clipboard   print   ?

       01.   <a> jQuery.fn.maxLength = function(max){
       02.       this.each(function(){
       03.           var type = this.tagName.toLowerCase();
       04.           var inputType = this.type? this.type.toLowerCase() : null;
       05.           if(type == "input" && inputType == "text" || inputType == "password"){
       06.               //Apply the standard maxLength
       07.               this.maxLength = max;
       08.           }
       09.           else if(type == "textarea"){
       10.               this.onkeypress = function(e){
       11.                   var ob = e || event;
       12.                   var keyCode = ob.keyCode;
       13.                   var hasSelection = document.selection? document.selection.createRange().text.length > 0
       14.                   return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 ||
       15.               };
       16.               this.onkeyup = function(){
       17.                   if(this.value.length > max){
       18.                       this.value = this.value.substring(0,max);
       19.                   }
       20.               };
       21.           }
       22.       });
       23.   };
       24.
       25.   //Usage:
       26.
       27.   $('#mytextarea').maxLength(500);
       28.   </a>


30.   How to create a basic test for a function
             view plain   copy to clipboard   print   ?

       01.   <a>
       02.       //Separate tests into modules.
       03.   module("Module B");
       04.
       05.   test("some other test", function() {
       06.     //Specify how many assertions are expected to run within a test.
       07.     expect(2);
       08.     //A comparison assertion, equivalent to JUnit's assertEquals.
       09.     equals( true, false, "failing test" );
       10.     equals( true, true, "passing test" );
       11.   });
       12.   </a>


31.   How to clone an element in jQuery:
             view plain   copy to clipboard   print   ?

       01.   <a>var cloned = $('#somediv').clone(); </a>


32.   How to test if an element is visible in jQuery:
             view plain   copy to clipboard   print   ?

       01.   <a>if($(element).is(':visible') == 'true') { //The element is Visible } </a>


33.   How to center an element on screen:
view plain   copy to clipboard   print   ?

       01.   <a>jQuery.fn.center = function () {
       02.       this.css('position','absolute');
       03.       this.css('top', ( $(window).height() ‐ this.height() ) / +$(window).scrollTop() + 'px');
       04.       this.css('left', ( $(window).width() ‐ this.width() ) / 2+$(window).scrollLeft() + 'px');
       05.       //Use the above function as: $(element).center(); </a>


34.   How to put the values of all the elements of a particular
      name into an array:
             view plain   copy to clipboard   print   ?

       01.   <a>
       02.          var arrInputValues = new Array();
       03.         $("input[name='table[]']").each(function(){
       04.           arrInputValues.push($(this).val());
       05.   });
       06.
       07.         </a>


35.   How to Strip HTML From Your Element
             view plain   copy to clipboard   print   ?

       01.   <a>
       02.       (function($) {
       03.       $.fn.stripHtml = function() {
       04.           var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
       05.           this.each(function() {
       06.               $(this).html(
       07.                   $(this).html().replace(regexp,”")
       08.               );
       09.           });
       10.           return $(this);
       11.       }
       12.   })(jQuery);
       13.
       14.         //usage:
       15.         $('p').stripHtml();
       16.
       17.         </a>


36.   How to get a parent element using closest:
             view plain   copy to clipboard   print   ?

       01.   <a>$('#searchBox').closest('div'); </a>




37.   How to log jQuery events using Firebug and Firefox:
view plain   copy to clipboard   print   ?

       01.   <a>
       02.   // Allows chainable logging
       03.   // Usage: $('#someDiv').hide().log('div hidden').addClass('someClass');
       04.   jQuery.log = jQuery.fn.log = function (msg) {
       05.         if (console){
       06.            console.log("%s: %o", msg, this);
       07.         }
       08.         return this;
       09.   };
       10.
       11.         </a>


38.   How to force links to open in a pop-up window:
             view plain   copy to clipboard   print   ?

       01.   <a>
       02.         jQuery('a.popup').live('click', function(){
       03.         newwindow=window.open($(this).attr('href'),'','height=200,width=150');
       04.         if (window.focus) {newwindow.focus()}
       05.         return false;
       06.   });
       07.
       08.         </a>


39.   How to force links to open in a new tab:
             view plain   copy to clipboard   print   ?

       01.   <a>
       02.   jQuery('a.newTab').live('click', function(){
       03.       newwindow=window.open($(this).href);
       04.       jQuery(this).target = "_blank";
       05.       return false;
       06.   });
       07.
       08.         </a>


40.   How to select siblings in jQuery using .siblings()
             view plain   copy to clipboard   print   ?

       01.   <a>
       02.   // Rather than doing this
       03.   $('#nav li').click(function(){
       04.       $('#nav li').removeClass('active');
       05.       $(this).addClass('active');
       06.   });
       07.
       08.   // Do this instead
       09.   $('#nav li').click(function(){
       10.       $(this).addClass('active')
       11.           .siblings().removeClass('active');
       12.   });
       13.       </a>




41.   How to Toggle All the checkboxes on a page:
view plain   copy to clipboard   print   ?

       01.   <a>var tog = false; // or true if they are checked on load
       02.   $('a').click(function() {
       03.       $("input[type=checkbox]").attr("checked",!tog);
       04.       tog = !tog;
       05.   });
       06.
       07.   </a>


42.   How to filter down a list of elements based on some
      input text:
             view plain   copy to clipboard   print   ?

       01.   <a>
       02.         //If the value of the element matches that of the entered text
       03.         //it will be returned
       04.         $('.someClass').filter(function() {
       05.         return $(this).attr('value') == $('input#someId').val() ;
       06.    })
       07.    </a>


43.   How to get mouse cursor X and Y
             view plain   copy to clipboard   print   ?

       01.   <a>$(document).mousemove(function(e){
       02.   $(document).ready(function() {
       03.   $().mousemove(function(e){
       04.   $(’#XY’).html(”X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY);
       05.   });
       06.   });</a>


44.   How to make an entire List Element (LI) clickable
             view plain   copy to clipboard   print   ?

       01.   <a>$("ul li").click(function(){
       02.     window.location=$(this).find("a").attr("href"); return false;
       03.   });
       04.   </a>

             view plain   copy to clipboard   print   ?

       01.   <ul><a>
       02.       </a><li><a href="#">Link 1</a></li>
       03.       <li><a href="#">Link 2</a></li>
       04.       <li><a href="#">Link 3</a></li>
       05.        <li><a href="#">Link 4</a></li>
       06.   </ul>




45.   How to Parse XML with jQuery (Basic example):
view plain   copy to clipboard   print   ?

       01.   function parseXml(xml) {
       02.       //find every Tutorial and print the author
       03.       $(xml).find("Tutorial").each(function()
       04.       {
       05.       $("#output").append($(this).attr("author") + "");
       06.       });
       07.   }
       08.
       09.


46.   How to Check if an image has been fully loaded:
             view plain   copy to clipboard   print   ?

       01.
       02.    $('#theImage').attr('src', 'image.jpg').load(function() {
       03.   alert('This Image Has Been Loaded');
       04.   });
       05.
       06.
       07.


47.   How to namespace events using jQuery:
             view plain   copy to clipboard   print   ?

       01.
       02.   //Events can be namespaced like this
       03.   $('input').bind('blur.validation', function(e){
       04.       // ...
       05.   });
       06.
       07.   //The data method also accept namespaces
       08.   $('input').data('validation.isValid', true);
       09.
       10.
       11.


48.   How to Check if Cookies Are Enabled Or Not:
             view plain   copy to clipboard   print   ?

       01.   var dt = new Date();
       02.   dt.setSeconds(dt.getSeconds() + 60);
       03.   document.cookie = "cookietest=1; expires=" + dt.toGMTString();
       04.   var cookiesEnabled = document.cookie.indexOf("cookietest=") != ‐1;
       05.   if(!cookiesEnabled)
       06.
       07.        //cookies have not been enabled
       08.   }


49.   How to Expire A Cookie:
             view plain   copy to clipboard   print   ?

       01.   var date = new Date();
       02.   date.setTime(date.getTime() + (x * 60 * 1000));
       03.   $.cookie('example', 'foo', { expires: date });
50.   Replace any URL on your page with a clickable link
               view plain   copy to clipboard   print   ?

        01.    $.fn.replaceUrl = function() {
        02.            var regexp = /((ftp|http|https)://(w+:{0,1}w*@)?(S+)(:[0‐9]+)?
               (/|/([w#!:.?+=&%@!‐/]))?)/gi;
        03.            this.each(function() {
        04.                $(this).html(
        05.                    $(this).html().replace(regexp,'<a href="$1">$1</a>‘)
        06.                );
        07.            });
        08.            return $(this);
        09.        }
        10.
        11.         //usage
        12.
        13.         $('p').replaceUrl();




Thanks for reading or printing out this article!. If you get a chance, remember that you can follow me at
http://www.twitter.com/addyosmani or follow my blog at AddyOsmani.com. You can also find me around
various jQuery Groups and Pages on Facebook, including jQuery Awesome. Thanks and happy coding!

Contenu connexe

Tendances

First Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentFirst Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentNuvole
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mockingKonstantin Kudryashov
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Formsdrubb
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 
Adopting 3D Touch in your apps
Adopting 3D Touch in your appsAdopting 3D Touch in your apps
Adopting 3D Touch in your appsJuan C Catalan
 
Symfony Messenger (Symfony Live San Francisco)
Symfony Messenger (Symfony Live San Francisco)Symfony Messenger (Symfony Live San Francisco)
Symfony Messenger (Symfony Live San Francisco)Samuel ROZE
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionNate Abele
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & RESTHugo Hamon
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Eventsdmethvin
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
Arquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com JetpackArquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com JetpackNelson Glauber Leal
 
UITableView Pain Points
UITableView Pain PointsUITableView Pain Points
UITableView Pain PointsKen Auer
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 

Tendances (20)

First Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentFirst Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven Development
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
 
Drupal 8: Forms
Drupal 8: FormsDrupal 8: Forms
Drupal 8: Forms
 
Bacbkone js
Bacbkone jsBacbkone js
Bacbkone js
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
Build your own entity with Drupal
Build your own entity with DrupalBuild your own entity with Drupal
Build your own entity with Drupal
 
Adopting 3D Touch in your apps
Adopting 3D Touch in your appsAdopting 3D Touch in your apps
Adopting 3D Touch in your apps
 
Symfony Messenger (Symfony Live San Francisco)
Symfony Messenger (Symfony Live San Francisco)Symfony Messenger (Symfony Live San Francisco)
Symfony Messenger (Symfony Live San Francisco)
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
BEAR DI
BEAR DIBEAR DI
BEAR DI
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Arquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com JetpackArquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com Jetpack
 
UITableView Pain Points
UITableView Pain PointsUITableView Pain Points
UITableView Pain Points
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 

En vedette

Hendri python
Hendri pythonHendri python
Hendri pythonChar Lie
 
To be an EVS-volunteer
To be an EVS-volunteerTo be an EVS-volunteer
To be an EVS-volunteerguestc730a3
 
Depaul EVS round-up 2014
Depaul EVS round-up 2014Depaul EVS round-up 2014
Depaul EVS round-up 2014Depaul Ireland
 
Cyberactivism & Social Media
Cyberactivism & Social MediaCyberactivism & Social Media
Cyberactivism & Social MediaIker Audicana
 
Module 1: Key Competencies of Effective Trainers
Module 1: Key Competencies of Effective TrainersModule 1: Key Competencies of Effective Trainers
Module 1: Key Competencies of Effective TrainersCardet1
 

En vedette (8)

European Youth Strategy 2010-2018
European Youth Strategy 2010-2018European Youth Strategy 2010-2018
European Youth Strategy 2010-2018
 
Hendri python
Hendri pythonHendri python
Hendri python
 
марта
мартамарта
марта
 
To be an EVS-volunteer
To be an EVS-volunteerTo be an EVS-volunteer
To be an EVS-volunteer
 
Depaul EVS round-up 2014
Depaul EVS round-up 2014Depaul EVS round-up 2014
Depaul EVS round-up 2014
 
Cyberactivism & Social Media
Cyberactivism & Social MediaCyberactivism & Social Media
Cyberactivism & Social Media
 
Module 1: Key Competencies of Effective Trainers
Module 1: Key Competencies of Effective TrainersModule 1: Key Competencies of Effective Trainers
Module 1: Key Competencies of Effective Trainers
 
Halloween
HalloweenHalloween
Halloween
 

Similaire à 50 jquery

Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScriptAndrew Dupont
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsEPAM Systems
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery ApplicationsRebecca Murphey
 
Jquery tutorial-beginners
Jquery tutorial-beginnersJquery tutorial-beginners
Jquery tutorial-beginnersIsfand yar Khan
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j queryMd. Ziaul Haq
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuerysergioafp
 
JQuery_and_Ajax.pptx
JQuery_and_Ajax.pptxJQuery_and_Ajax.pptx
JQuery_and_Ajax.pptxAditiPawale1
 
Jquery Best Practices
Jquery Best PracticesJquery Best Practices
Jquery Best Practicesbrinsknaps
 
Selenium interview questions and answers
Selenium interview questions and answersSelenium interview questions and answers
Selenium interview questions and answerskavinilavuG
 
A to Z about JQuery - Become Newbie to Expert Java Developer
A to Z about JQuery - Become Newbie to Expert Java DeveloperA to Z about JQuery - Become Newbie to Expert Java Developer
A to Z about JQuery - Become Newbie to Expert Java DeveloperManoj Bhuva
 
jQuery in the [Aol.] Enterprise
jQuery in the [Aol.] EnterprisejQuery in the [Aol.] Enterprise
jQuery in the [Aol.] EnterpriseDave Artz
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tipsanubavam-techkt
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuerySeble Nigussie
 
jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)Addy Osmani
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQueryKnoldus Inc.
 
How to increase Performance of Web Application using JQuery
How to increase Performance of Web Application using JQueryHow to increase Performance of Web Application using JQuery
How to increase Performance of Web Application using JQuerykolkatageeks
 

Similaire à 50 jquery (20)

Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Jquery tutorial-beginners
Jquery tutorial-beginnersJquery tutorial-beginners
Jquery tutorial-beginners
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j query
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
jQuery
jQueryjQuery
jQuery
 
JQuery_and_Ajax.pptx
JQuery_and_Ajax.pptxJQuery_and_Ajax.pptx
JQuery_and_Ajax.pptx
 
Eclipse Tricks
Eclipse TricksEclipse Tricks
Eclipse Tricks
 
Jquery Best Practices
Jquery Best PracticesJquery Best Practices
Jquery Best Practices
 
Selenium interview questions and answers
Selenium interview questions and answersSelenium interview questions and answers
Selenium interview questions and answers
 
A to Z about JQuery - Become Newbie to Expert Java Developer
A to Z about JQuery - Become Newbie to Expert Java DeveloperA to Z about JQuery - Become Newbie to Expert Java Developer
A to Z about JQuery - Become Newbie to Expert Java Developer
 
Backbone js
Backbone jsBackbone js
Backbone js
 
jQuery in the [Aol.] Enterprise
jQuery in the [Aol.] EnterprisejQuery in the [Aol.] Enterprise
jQuery in the [Aol.] Enterprise
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tips
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
jQuery Best Practice
jQuery Best Practice jQuery Best Practice
jQuery Best Practice
 
jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)jQuery Performance Tips and Tricks (2011)
jQuery Performance Tips and Tricks (2011)
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQuery
 
How to increase Performance of Web Application using JQuery
How to increase Performance of Web Application using JQueryHow to increase Performance of Web Application using JQuery
How to increase Performance of Web Application using JQuery
 

Dernier

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Dernier (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

50 jquery

  • 1. 1. How to Create A Nested Filter: view plain copy to clipboard print ? 01. //a filter allows you to reduce the set of matched elements 02. //to those that match a given selector. In this case the query 03. //removes anything which doesn't (:not) have (:has) a child with 04. //class "selected" (.selected) 05. 06. .filter(":not(:has(.selected))") 2. How to Reuse Your Element Searches view plain copy to clipboard print ? 01. var allItems = $("div.item"); 02. var keepList = $("div#container1 div.item"); 03. 04. //Now you can keep working with those jQuery objects. For example, 05. //trim down the "keep list" based on checkboxes whose names 06. //correspond to <div> class names: 07. 08. $(formToLookAt + " input:checked").each(function() { 09. keepListkeepList = keepList.filter("." + $(this).attr("name")); 10. }); 11. </div> 3. How To Check If An Element contains a certain class or element with has(): view plain copy to clipboard print ? 01. //jQuery 1.4.* includes support for the has method. This method will find 02. //if a an element contains a certain other element class or whatever it is 03. //you are looking for and do anything you want to them. 04. 05. $("input").has(".email").addClass("email_icon"); 4. How to Switch StyleSheets With jQuery:
  • 2. view plain copy to clipboard print ? 01. //Look for the media‐type you wish to switch then set the href to your new style sheet 02. $('link[media='screen']').attr('href', 'Alternative.css'); 5. How to Limit the Scope of Selection (For Optimization): view plain copy to clipboard print ? 01. //Where possible, pre‐fix your class names with a tag name 02. //so that jQuery doesn't have to spend more time searching 03. //for the element you're after. Also remember that anything 04. //you can do to be more specific about where the element is 05. //on your page will cut down on execution/search times 06. 07. var in_stock = $('#shopping_cart_items input.is_in_stock'); view plain copy to clipboard print ? 01. <ul id="shopping_cart_items"> 02. <li><input class="is_in_stock" name="item" value="Item‐X" type="radio"> Item X</li> 03. <li><input class="3‐5_days" name="item" value="Item‐Y" type="radio"> Item Y</li> 04. <li><input class="unknown" name="item" value="Item‐Z" type="radio"> Item Z</li> 05. </ul> 06. 6. How to Correctly Use ToggleClass: view plain copy to clipboard print ? 01. //Toggle class allows you to add or remove a class 02. //from an element depending on the presence of that 03. //class. Where some developers would use: 04. 05. a.hasClass('blueButton') ? a.removeClass('blueButton') : a.addClass('blueButton'); 06. 07. //toggleClass allows you to easily do this using 08. 09. a.toggleClass('blueButton'); 7. How to set an IE Specific Function: view plain copy to clipboard print ? 01. if ($.browser.msie) { // Internet Explorer is a sadist. } 8. How to Replace an element with jQuery: view plain copy to clipboard print ? 01. $('#thatdiv').replaceWith('fnuh'); 9. How to Verify if an element is empty: view plain copy to clipboard print ? 01. if ($('#keks').html()) { //Nothing found ;} 10. How to find out the index of an element in an unordered set
  • 3. view plain copy to clipboard print ? 01. $("ul > li").click(function () { 02. var index = $(this).prevAll().length; 03. }); 11. How to Bind a function to an event: view plain copy to clipboard print ? 01. $('#foo').bind('click', function() { 02. alert('User clicked on "foo."'); 03. }); 12. How to Append or add HTML to an element: view plain copy to clipboard print ? 01. $('#lal').append('sometext'); 13. How to use an object literal to define properties when creating an element view plain copy to clipboard print ? 01. var e = $("<a>", { href: "#", class: "a‐class another‐class", title: "..." }); 02. </a> 14. How to Filter using multiple-attributes view plain copy to clipboard print ? 01. <a> 02. //This precision‐based approached can be useful when you use 03. //lots of similar input elements which have different types 04. var elements = $('#someid input[type=sometype][value=somevalue]').get(); 05. </a> 15. How to Preload images with jQuery: view plain copy to clipboard print ? 01. <a> 02. jQuery.preloadImages = function() { for(var i = 0; i').attr('src', arguments[i]); } }; 03. 04. // Usage $.preloadImages('image1.gif', '/path/to/image2.png', 'some/image3.jpg'); 05. </a> 16. How to set an event handler for any element that matches a selector:
  • 4. view plain copy to clipboard print ? 01. <a>$('button.someClass').live('click', someFunction); 02. 03. //Note that in jQuery 1.4.2, the delegate and undelegate options have been 04. //introduced to replace live as they offer better support for context 05. 06. //For example, in terms of a table where before you would use.. 07. 08. // .live() 09. $("table").each(function(){ 10. $("td", this).live("hover", function(){ 11. $(this).toggleClass("hover"); 12. }); 13. }); 14. 15. //Now use.. 16. 17. $("table").delegate("td", "hover", function(){ 18. $(this).toggleClass("hover"); 19. }); 20. 21. </a> 17. How to find an option element that's been selected: view plain copy to clipboard print ? 01. <a> $('#someElement').find('option:selected'); 02. </a> 18. How to hide an element that contains text of a certain value: view plain copy to clipboard print ? 01. <a>$("p.value:contains('thetextvalue')").hide();</a> 19. How To AutoScroll to a section of your page: view plain copy to clipboard print ? 01. <a>jQuery.fn.autoscroll = function(selector) { 02. $('html,body').animate( 03. {scrollTop: $(selector).offset().top}, 04. 500 05. ); 06. } 07. 08. //Then to scroll to the class/area you wish to get to like this: 09. $('.area_name').autoscroll(); 10. </a> 20. How To Detect Any Browser: view plain copy to clipboard print ? 01. <a> Detect Safari (if( $.browser.safari)), 02. Detect IE6 and over (if ($.browser.msie && $.browser.version > 6 )), 03. Detect IE6 and below (if ($.browser.msie && $.browser.version <= 6 )), 04. Detect FireFox 2 and above (if ($.browser.mozilla && $.browser.version >= '1.8' ))</a>
  • 5. 21. How To Replace a word in a string: view plain copy to clipboard print ? 01. <a>var el = $('#id'); 02. el.html(el.html().replace(/word/ig, ''));</a> 22. How To Disable right-click contextual menu : view plain copy to clipboard print ? 01. <a>$(document).bind('contextmenu',function(e){ return false; });</a> 23. How to define a Custom Selector view plain copy to clipboard print ? 01. <a> $.expr[':'].mycustomselector = function(element, index, meta, stack){ 02. // element‐ is a DOM element 03. // index ‐ the current loop index in stack 04. // meta ‐ meta data about your selector 05. // stack ‐ stack of all elements to loop 06. 07. // Return true to include current element 08. // Return false to explude current element 09. }; 10. 11. // Custom Selector usage: 12. $('.someClasses:test').doSomething(); 13. </a> 24. How to check if an element exists view plain copy to clipboard print ? 01. <a>if ($('#someDiv').length) {//hooray!!! it exists...}</a> 25. How to Detect Both Right & Left Mouse-clicks with jQuery: view plain copy to clipboard print ? 01. <a>$("#someelement").live('click', function(e) { 02. if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) { 03. alert("Left Mouse Button Clicked"); 04. } 05. else if(e.button == 2) 06. alert("Right Mouse Button Clicked"); 07. }); 08. 09. </a> 26. How To Show or Erase a Default Value In An Input Field:
  • 6. view plain copy to clipboard print ? 01. <a>//This snippet will show you how to keep a default value 02. //in a text input field for when a user hasn't entered in 03. //a value to replace it 04. 05. swap_val = []; 06. $(".swap").each(function(i){ 07. swap_val[i] = $(this).val(); 08. $(this).focusin(function(){ 09. if ($(this).val() == swap_val[i]) { 10. $(this).val(""); 11. } 12. }).focusout(function(){ 13. if ($.trim($(this).val()) == "") { 14. $(this).val(swap_val[i]); 15. } 16. }); 17. }); 18. </a> view plain copy to clipboard print ? 01. <a><input class="swap" value="Enter Username here.." type="text"> 02. </a> 27. How To Automatically Hide or Close Elements After An Amount Of Time (supports 1.4): view plain copy to clipboard print ? 01. <a> 02. //Here's how we used to do it in 1.3.2 using setTimeout 03. setTimeout(function() { 04. $('.mydiv').hide('blind', {}, 500) 05. }, 5000); 06. 07. //And here's how you can do it with 1.4 using the delay() feature (this is a lot like sleep) 08. $(".mydiv").delay(5000).hide('blind', {}, 500); 09. </a> 28. How To Add Dynamically Created Elements to the DOM: view plain copy to clipboard print ? 01. <a> var newDiv = $(''); 02. newDiv.attr('id','myNewDiv').appendTo('body'); </a> 29. How To Limit The Number Of Characters in a "Text-Area" field:
  • 7. view plain copy to clipboard print ? 01. <a> jQuery.fn.maxLength = function(max){ 02. this.each(function(){ 03. var type = this.tagName.toLowerCase(); 04. var inputType = this.type? this.type.toLowerCase() : null; 05. if(type == "input" && inputType == "text" || inputType == "password"){ 06. //Apply the standard maxLength 07. this.maxLength = max; 08. } 09. else if(type == "textarea"){ 10. this.onkeypress = function(e){ 11. var ob = e || event; 12. var keyCode = ob.keyCode; 13. var hasSelection = document.selection? document.selection.createRange().text.length > 0 14. return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || 15. }; 16. this.onkeyup = function(){ 17. if(this.value.length > max){ 18. this.value = this.value.substring(0,max); 19. } 20. }; 21. } 22. }); 23. }; 24. 25. //Usage: 26. 27. $('#mytextarea').maxLength(500); 28. </a> 30. How to create a basic test for a function view plain copy to clipboard print ? 01. <a> 02. //Separate tests into modules. 03. module("Module B"); 04. 05. test("some other test", function() { 06. //Specify how many assertions are expected to run within a test. 07. expect(2); 08. //A comparison assertion, equivalent to JUnit's assertEquals. 09. equals( true, false, "failing test" ); 10. equals( true, true, "passing test" ); 11. }); 12. </a> 31. How to clone an element in jQuery: view plain copy to clipboard print ? 01. <a>var cloned = $('#somediv').clone(); </a> 32. How to test if an element is visible in jQuery: view plain copy to clipboard print ? 01. <a>if($(element).is(':visible') == 'true') { //The element is Visible } </a> 33. How to center an element on screen:
  • 8. view plain copy to clipboard print ? 01. <a>jQuery.fn.center = function () { 02. this.css('position','absolute'); 03. this.css('top', ( $(window).height() ‐ this.height() ) / +$(window).scrollTop() + 'px'); 04. this.css('left', ( $(window).width() ‐ this.width() ) / 2+$(window).scrollLeft() + 'px'); 05. //Use the above function as: $(element).center(); </a> 34. How to put the values of all the elements of a particular name into an array: view plain copy to clipboard print ? 01. <a> 02. var arrInputValues = new Array(); 03. $("input[name='table[]']").each(function(){ 04. arrInputValues.push($(this).val()); 05. }); 06. 07. </a> 35. How to Strip HTML From Your Element view plain copy to clipboard print ? 01. <a> 02. (function($) { 03. $.fn.stripHtml = function() { 04. var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi; 05. this.each(function() { 06. $(this).html( 07. $(this).html().replace(regexp,”") 08. ); 09. }); 10. return $(this); 11. } 12. })(jQuery); 13. 14. //usage: 15. $('p').stripHtml(); 16. 17. </a> 36. How to get a parent element using closest: view plain copy to clipboard print ? 01. <a>$('#searchBox').closest('div'); </a> 37. How to log jQuery events using Firebug and Firefox:
  • 9. view plain copy to clipboard print ? 01. <a> 02. // Allows chainable logging 03. // Usage: $('#someDiv').hide().log('div hidden').addClass('someClass'); 04. jQuery.log = jQuery.fn.log = function (msg) { 05. if (console){ 06. console.log("%s: %o", msg, this); 07. } 08. return this; 09. }; 10. 11. </a> 38. How to force links to open in a pop-up window: view plain copy to clipboard print ? 01. <a> 02. jQuery('a.popup').live('click', function(){ 03. newwindow=window.open($(this).attr('href'),'','height=200,width=150'); 04. if (window.focus) {newwindow.focus()} 05. return false; 06. }); 07. 08. </a> 39. How to force links to open in a new tab: view plain copy to clipboard print ? 01. <a> 02. jQuery('a.newTab').live('click', function(){ 03. newwindow=window.open($(this).href); 04. jQuery(this).target = "_blank"; 05. return false; 06. }); 07. 08. </a> 40. How to select siblings in jQuery using .siblings() view plain copy to clipboard print ? 01. <a> 02. // Rather than doing this 03. $('#nav li').click(function(){ 04. $('#nav li').removeClass('active'); 05. $(this).addClass('active'); 06. }); 07. 08. // Do this instead 09. $('#nav li').click(function(){ 10. $(this).addClass('active') 11. .siblings().removeClass('active'); 12. }); 13. </a> 41. How to Toggle All the checkboxes on a page:
  • 10. view plain copy to clipboard print ? 01. <a>var tog = false; // or true if they are checked on load 02. $('a').click(function() { 03. $("input[type=checkbox]").attr("checked",!tog); 04. tog = !tog; 05. }); 06. 07. </a> 42. How to filter down a list of elements based on some input text: view plain copy to clipboard print ? 01. <a> 02. //If the value of the element matches that of the entered text 03. //it will be returned 04. $('.someClass').filter(function() { 05. return $(this).attr('value') == $('input#someId').val() ; 06. }) 07. </a> 43. How to get mouse cursor X and Y view plain copy to clipboard print ? 01. <a>$(document).mousemove(function(e){ 02. $(document).ready(function() { 03. $().mousemove(function(e){ 04. $(’#XY’).html(”X Axis : ” + e.pageX + ” | Y Axis ” + e.pageY); 05. }); 06. });</a> 44. How to make an entire List Element (LI) clickable view plain copy to clipboard print ? 01. <a>$("ul li").click(function(){ 02. window.location=$(this).find("a").attr("href"); return false; 03. }); 04. </a> view plain copy to clipboard print ? 01. <ul><a> 02. </a><li><a href="#">Link 1</a></li> 03. <li><a href="#">Link 2</a></li> 04. <li><a href="#">Link 3</a></li> 05. <li><a href="#">Link 4</a></li> 06. </ul> 45. How to Parse XML with jQuery (Basic example):
  • 11. view plain copy to clipboard print ? 01. function parseXml(xml) { 02. //find every Tutorial and print the author 03. $(xml).find("Tutorial").each(function() 04. { 05. $("#output").append($(this).attr("author") + ""); 06. }); 07. } 08. 09. 46. How to Check if an image has been fully loaded: view plain copy to clipboard print ? 01. 02. $('#theImage').attr('src', 'image.jpg').load(function() { 03. alert('This Image Has Been Loaded'); 04. }); 05. 06. 07. 47. How to namespace events using jQuery: view plain copy to clipboard print ? 01. 02. //Events can be namespaced like this 03. $('input').bind('blur.validation', function(e){ 04. // ... 05. }); 06. 07. //The data method also accept namespaces 08. $('input').data('validation.isValid', true); 09. 10. 11. 48. How to Check if Cookies Are Enabled Or Not: view plain copy to clipboard print ? 01. var dt = new Date(); 02. dt.setSeconds(dt.getSeconds() + 60); 03. document.cookie = "cookietest=1; expires=" + dt.toGMTString(); 04. var cookiesEnabled = document.cookie.indexOf("cookietest=") != ‐1; 05. if(!cookiesEnabled) 06. 07. //cookies have not been enabled 08. } 49. How to Expire A Cookie: view plain copy to clipboard print ? 01. var date = new Date(); 02. date.setTime(date.getTime() + (x * 60 * 1000)); 03. $.cookie('example', 'foo', { expires: date });
  • 12. 50. Replace any URL on your page with a clickable link view plain copy to clipboard print ? 01. $.fn.replaceUrl = function() { 02. var regexp = /((ftp|http|https)://(w+:{0,1}w*@)?(S+)(:[0‐9]+)? (/|/([w#!:.?+=&%@!‐/]))?)/gi; 03. this.each(function() { 04. $(this).html( 05. $(this).html().replace(regexp,'<a href="$1">$1</a>‘) 06. ); 07. }); 08. return $(this); 09. } 10. 11. //usage 12. 13. $('p').replaceUrl(); Thanks for reading or printing out this article!. If you get a chance, remember that you can follow me at http://www.twitter.com/addyosmani or follow my blog at AddyOsmani.com. You can also find me around various jQuery Groups and Pages on Facebook, including jQuery Awesome. Thanks and happy coding!