You are on page 1of 12

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!

You might also like