50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

12
How to Create A Nested Filter: view plain copy to clipboard print ? //a filter allows you to reduce the set of matched elements 01. //to those that match a given selector. In this case the query 02. //removes anything which doesn't (:not) have (:has) a child with 03. //class "selected" (.selected) 04. 05. .filter(":not(:has(.selected))") 06. 1. How to Reuse Your Element Searches view plain copy to clipboard print ? var allItems = $("div.item"); 01. var keepList = $("div#container1 div.item"); 02. 03. //Now you can keep working with those jQuery objects. For example, 04. //trim down the "keep list" based on checkboxes whose names 05. //correspond to <div> class names: 06. 07. $(formToLookAt + " input:checked").each(function() { 08. keepListkeepList = keepList.filter("." + $(this).attr("name")); 09. }); 10. </div> 11. 2. How To Check If An Element contains a certain class or element with has(): view plain copy to clipboard print ? //jQuery 1.4.* includes support for the has method. This method will find 01. //if a an element contains a certain other element class or whatever it is 02. //you are looking for and do anything you want to them. 03. 04. $("input").has(".email").addClass("email_icon"); 05. 3. How to Switch StyleSheets With jQuery: 4.

description

This print-optimized article was lucky enough to be retweeted 250 times in it's first week of publishing. Here, I would like to offer readers a print-optimized version which will help you to learn from these 50 jQuery snippets based on jQuery 1.3.2 and 1.4.2. I hope you enjoy it!.

Transcript of 50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

Page 1: 50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

How to Create A Nested Filter:

view plain copy to clipboard print ?

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

1.

How to Reuse Your Element Searches

view plain copy to clipboard print ?

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

2.

How To Check If An Element contains a certain class orelement with has():

view plain copy to clipboard print ?

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

3.

How to Switch StyleSheets With jQuery:4.

Page 2: 50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

view plain copy to clipboard print ?

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

How to Limit the Scope of Selection (ForOptimization):

view plain copy to clipboard print ?

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

view plain copy to clipboard print ?

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

5.

How to Correctly Use ToggleClass:

view plain copy to clipboard print ?

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

6.

How to set an IE Specific Function:

view plain copy to clipboard print ?

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

7.

How to Replace an element with jQuery:

view plain copy to clipboard print ?

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

8.

How to Verify if an element is empty:

view plain copy to clipboard print ?

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

9.

How to find out the index of an element in anunordered set

10.

Page 3: 50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

view plain copy to clipboard print ?

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

How to Bind a function to an event:

view plain copy to clipboard print ?

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

11.

How to Append or add HTML to an element:

view plain copy to clipboard print ?

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

12.

How to use an object literal to define properties whencreating an element

view plain copy to clipboard print ?

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

13.

How to Filter using multiple-attributes

view plain copy to clipboard print ?

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

14.

How to Preload images with jQuery:

view plain copy to clipboard print ?

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

15.

How to set an event handler for any element thatmatches a selector:

16.

Page 4: 50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

view plain copy to clipboard print ?

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

How to find an option element that's been selected:

view plain copy to clipboard print ?

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

17.

How to hide an element that contains text of a certainvalue:

view plain copy to clipboard print ?

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

18.

How To AutoScroll to a section of your page:

view plain copy to clipboard print ?

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

19.

How To Detect Any Browser:

view plain copy to clipboard print ?

<a> Detect Safari (if( $.browser.safari)), 01. Detect IE6 and over (if ($.browser.msie && $.browser.version > 6 )), 02. Detect IE6 and below (if ($.browser.msie && $.browser.version <= 6 )), 03. Detect FireFox 2 and above (if ($.browser.mozilla && $.browser.version >= '1.8' ))</a> 04.

20.

Page 5: 50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

How To Replace a word in a string:

view plain copy to clipboard print ?

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

21.

How To Disable right-click contextual menu :

view plain copy to clipboard print ?

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

22.

How to define a Custom Selector

view plain copy to clipboard print ?

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

23.

How to check if an element exists

view plain copy to clipboard print ?

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

24.

How to Detect Both Right & Left Mouse-clicks withjQuery:

view plain copy to clipboard print ?

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

25.

How To Show or Erase a Default Value In An InputField:

26.

Page 6: 50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

view plain copy to clipboard print ?

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

view plain copy to clipboard print ?

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

How To Automatically Hide or Close Elements After AnAmount Of Time (supports 1.4):

view plain copy to clipboard print ?

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

27.

How To Add Dynamically Created Elements to theDOM:

view plain copy to clipboard print ?

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

28.

How To Limit The Number Of Characters in a"Text-Area" field:

29.

Page 7: 50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

view plain copy to clipboard print ?

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

How to create a basic test for a function

view plain copy to clipboard print ?

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

30.

How to clone an element in jQuery:

view plain copy to clipboard print ?

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

31.

How to test if an element is visible in jQuery:

view plain copy to clipboard print ?

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

32.

How to center an element on screen:33.

Page 8: 50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

view plain copy to clipboard print ?

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

How to put the values of all the elements of a particularname into an array:

view plain copy to clipboard print ?

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

34.

How to Strip HTML From Your Element

view plain copy to clipboard print ?

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

35.

How to get a parent element using closest:

view plain copy to clipboard print ?

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

36.

How to log jQuery events using Firebug and Firefox:37.

Page 9: 50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

view plain copy to clipboard print ?

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

How to force links to open in a pop-up window:

view plain copy to clipboard print ?

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

38.

How to force links to open in a new tab:

view plain copy to clipboard print ?

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

39.

How to select siblings in jQuery using .siblings()

view plain copy to clipboard print ?

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

40.

How to Toggle All the checkboxes on a page:41.

Page 10: 50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

view plain copy to clipboard print ?

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

How to filter down a list of elements based on someinput text:

view plain copy to clipboard print ?

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

42.

How to get mouse cursor X and Y

view plain copy to clipboard print ?

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

43.

How to make an entire List Element (LI) clickable

view plain copy to clipboard print ?

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

view plain copy to clipboard print ?

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

44.

How to Parse XML with jQuery (Basic example):45.

Page 11: 50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

view plain copy to clipboard print ?

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

How to Check if an image has been fully loaded:

view plain copy to clipboard print ?

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

46.

How to namespace events using jQuery:

view plain copy to clipboard print ?

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

47.

How to Check if Cookies Are Enabled Or Not:

view plain copy to clipboard print ?

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

48.

How to Expire A Cookie:

view plain copy to clipboard print ?

var date = new Date(); 01.date.setTime(date.getTime() + (x * 60 * 1000)); 02.$.cookie('example', 'foo', { expires: date }); 03.

49.

Page 12: 50 jQuery Snippets That Will Help Make You A Better JavaScript Developer

Replace any URL on your page with a clickable link

view plain copy to clipboard print ?

$.fn.replaceUrl = function() { 01. var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0‐9]+)?(\/|\/([\w#!:.?+=&%@!\‐\/]))?)/gi;

02.

this.each(function() { 03. $(this).html( 04. $(this).html().replace(regexp,'<a href="$1">$1</a>‘) 05. ); 06. }); 07. return $(this); 08. } 09. 10. //usage 11. 12. $('p').replaceUrl(); 13.

50.

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!