50 jQuery Snippets

  • Upload
    kzelda

  • View
    215

  • Download
    0

Embed Size (px)

Citation preview

  • 8/8/2019 50 jQuery Snippets

    1/11

    In todays post Im going to show you guys 50 jQuery Snippets that can help you with your JavaScript

    projects. Some of these snippets are going to be things that have just been supported with jQuery 1.4.2

    whilst others are really useful functions or methods that can help you do things better or quicker. Ive tried

    to bare in mind optimal performance with these snippets so if theres anything you see that you think

    could be done better, please feel free to post your version in the comments!. I hope you find the post

    useful.

    How to Create A Nested Filter:

    view plain copy to clipboard print ?

    //a filter allows you to reduce the set of matched elements01.//to those that match a given selector. In this case the query02.//removes anything which doesn't (:not) have (:has) a child with03.//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 names05.

    //correspond to06.class names:07.08.$(formToLookAt + " input:checked").each(function() { keepListkeepList = kee09.

    2.

    Query Snippets That Will Help You Become A Better JavaScript D... file:///C:/jq/50.ht

    r 11 05/01/2011 10:03

  • 8/8/2019 50 jQuery Snippets

    2/11

    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 find01.//if a an element contains a certain other element class or whatever it is02.//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:

    view plain copy to clipboard print ?

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

    4.

    How to Limit the Scope of Selection (For Optimization):

    view plain copy to clipboard print ?

    //Where possible, pre-fix your class names with a tag name01.//so that jQuery doesn't have to spend more time searching02.//for the element you're after. Also remember that anything03.//you can do to be more specific about where the element is04.//on your page will cut down on execution/search times05.06.var in_stock = $('#shopping_cart_items input.is_in_stock');07.

    view plain copy to clipboard print ?

    01. 02.

    Item X03.

    04.

    Item Y05.

    06. Item Z07.

    08.

    5.

    How to Correctly Use ToggleClass:

    view plain copy to clipboard print ?

    //Toggle class allows you to add or remove a class01.//from an element depending on the presence of that02.//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 using07.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.

    Query Snippets That Will Help You Become A Better JavaScript D... file:///C:/jq/50.ht

    r 11 05/01/2011 10:03

  • 8/8/2019 50 jQuery Snippets

    3/11

    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 an unordered set

    view plain copy to clipboard print ?

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

    10.

    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 when creating

    an element

    view plain copy to clipboard print ?

    var e = $("", { href: "#", class: "a-class another-class", title: "..." });01.

    13.

    How to Filter using multiple-attributes

    view plain copy to clipboard print ?

    //This precision-based approached can be useful when you use01.//lots of similar input elements which have different types02.

    var elements = $('#someid input[type=sometype][value=somevalue]').get();03.

    14.

    How to Preload images with jQuery:

    view plain copy to clipboard print ?

    jQuery.preloadImages = function() { for(var i = 0; i').attr('src', arguments[i])01.02.// Usage $.preloadImages('image1.gif', '/path/to/image2.png', 'some/image3.jpg');

    03.

    15.

    Query Snippets That Will Help You Become A Better JavaScript D... file:///C:/jq/50.ht

    r 11 05/01/2011 10:03

  • 8/8/2019 50 jQuery Snippets

    4/11

    How to set an event handler for any element that matches a

    selector:

    view plain copy to clipboard print ?

    $('button.someClass').live('click', someFunction);01.02. //Note that in jQuery 1.4.2, the delegate and undelegate options have been03.

    //introduced to replace live as they offer better support for context04.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.

    16.

    How to find an option element thats been selected:

    view plain copy to clipboard print ?

    $('#someElement').find('option:selected');01.

    17.

    How to hide an element that contains text of a certain value:

    view plain copy to clipboard print ?

    $("p.value:contains('thetextvalue')").hide();01.

    18.

    How To AutoScroll to a section of your page:

    view plain copy to clipboard print ?

    jQuery.fn.autoscroll = function(selector) {01.$('html,body').animate(02.

    {scrollTop: $(selector).offset().top},03.50004.

    );05.}06.07.//Then to scroll to the class/area you wish to get to like this:08.$('.area_name').autoscroll();09.

    19.

    How To Detect Any Browser:

    view plain copy to clipboard print ?

    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 = '1.8'04.

    20.

    How To Replace a word in a string:21.

    Query Snippets That Will Help You Become A Better JavaScript D... file:///C:/jq/50.ht

    r 11 05/01/2011 10:03

  • 8/8/2019 50 jQuery Snippets

    5/11

    view plain copy to clipboard print ?

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

    How To Disable right-click contextual menu :

    view plain copy to clipboard print ?

    $(document).bind('contextmenu',function(e){ returnfalse; });01.

    22.

    How to define a Custom Selector

    view plain copy to clipboard print ?

    $.expr[':'].mycustomselector = function(element, index, meta, stack){01. // element- is a DOM element02. // index - the current loop index in stack03. // meta - meta data about your selector04. // stack - stack of all elements to loop05.06.

    // Return true to include current element07. // Return false to explude current element08.};09.10.// Custom Selector usage:11.$('.someClasses:test').doSomething();12.

    23.

    How to check if an element exists

    view plain copy to clipboard print ?

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

    24.

    How to Detect Both Right & Left Mouse-clicks with jQuery:

    view plain copy to clipboard print ?

    $("#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.

    elseif(e.button == 2)05.alert("Right Mouse Button Clicked");06.

    });07.

    25.

    How To Show or Erase a Default Value In An Input Field:26.

    Query Snippets That Will Help You Become A Better JavaScript D... file:///C:/jq/50.ht

    r 11 05/01/2011 10:03

  • 8/8/2019 50 jQuery Snippets

    6/11

    view plain copy to clipboard print ?

    //This snippet will show you how to keep a default value01.//in a text input field for when a user hasn't entered in02.//a value to replace it03.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.

    view plain copy to clipboard print ?

    01.

    How To Automatically Hide or Close Elements After An

    Amount Of Time (supports 1.4):

    view plain copy to clipboard print ?

    //Here's how we used to do it in 1.3.2 using setTimeout01.

    setTimeout(function() {02.$('.mydiv').hide('blind', {}, 500)03.

    }, 5000);04.05.

    //And here's how you can do it with 1.4 using the delay() feature (this is a lo06.

    $(".mydiv").delay(5000).hide('blind', {}, 500);07. 08.

    27.

    How To Add Dynamically Created Elements to the DOM:

    view plain copy to clipboard print ?

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

    28.

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

    field:

    29.

    Query Snippets That Will Help You Become A Better JavaScript D... file:///C:/jq/50.ht

    r 11 05/01/2011 10:03

  • 8/8/2019 50 jQuery Snippets

    7/11

    view plain copy to clipboard print ?

    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 maxLength06.

    this.maxLength = max;07.}08.

    elseif(type == "textarea"){09. this.onkeypress = function(e){10. var ob = e || event;11.

    var keyCode = ob.keyCode;12.

    var hasSelection = document.selection? document.selection.creat13.

    return !(this.value.length >= max && (keyCode > 50 || 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.

    How to create a basic test for a function

    view plain copy to clipboard print ?

    //Separate tests into modules.01.module("Module B");02.03.

    test("some other test", function() {04. //Specify how many assertions are expected to run within a test.05.

    expect(2);06. //A comparison assertion, equivalent to JUnit's assertEquals.07.

    equals( true, false, "failing test" );08.

    equals( true, true, "passing test" );09.});10.

    30.

    How to clone an element in jQuery:

    view plain copy to clipboard print ?

    var cloned = $('#somediv').clone();01.

    31.

    How to test if an element is visible in jQuery:

    view plain copy to clipboard print ?

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

    32.

    How to center an element on screen:33.

    Query Snippets That Will Help You Become A Better JavaScript D... file:///C:/jq/50.ht

    r 11 05/01/2011 10:03

  • 8/8/2019 50 jQuery Snippets

    8/11

    view plain copy to clipboard print ?

    jQuery.fn.center = function () {01.

    this.css('position','absolute');02.

    this.css('top', ( $(window).height() - this.height() ) / +$(window).scrollT03.

    this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollL04. //Use the above function as: $(element).center();05.

    How to put the values of all the elements of a particular name

    into an array:

    view plain copy to clipboard print ?

    var arrInputValues = new Array();01.

    $("input[name='table\\[\\]']").each(function(){02.

    arrInputValues.push($(this).val());03.);04.

    34.

    How to Strip HTML From Your Element

    view plain copy to clipboard print ?

    (function($) {01.

    $.fn.stripHtml = function() {02. var regexp = /])*>/gi;03.

    this.each(function() {04.

    $(this).html(05.

    $(this).html().replace(regexp,")06.);07.

    });08.

    return $(this);09.}10.

    })(jQuery);11.12.

    //usage:13.$('p').stripHtml();14.

    35.

    How to get a parent element using closest:

    view plain copy to clipboard print ?

    $('#searchBox').closest('div');01.

    36.

    How to log jQuery events using Firebug and Firefox:

    view plain copy to clipboard print ?

    // Allows chainable logging01.// Usage: $('#someDiv').hide().log('div hidden').addClass('someClass');02.

    jQuery.log = jQuery.fn.log = function (msg) {03. if (console){04.

    console.log("%s: %o", msg, this);05.}06.

    returnthis;07.};08.

    37.

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

    Query Snippets That Will Help You Become A Better JavaScript D... file:///C:/jq/50.ht

    r 11 05/01/2011 10:03

  • 8/8/2019 50 jQuery Snippets

    9/11

    view plain copy to clipboard print ?

    jQuery('a.popup').live('click', function(){01.

    newwindow=window.open($(this).attr('href'),'','height=200,width=150');02.

    if (window.focus) {newwindow.focus()}03.

    returnfalse;04.});05.

    How to force links to open in a new tab:

    view plain copy to clipboard print ?

    jQuery('a.newTab').live('click', function(){01.

    newwindow=window.open($(this).href);02.jQuery(this).target = "_blank";03.

    returnfalse;04.});05.

    39.

    How to select siblings in jQuery using .siblings()

    view plain copy to clipboard print ?

    // Rather than doing this01.

    $('#nav li').click(function(){02.$('#nav li').removeClass('active');03.$(this).addClass('active');04.

    });05.06.// Do this instead07.$('#nav li').click(function(){08.

    $(this).addClass('active')09..siblings().removeClass('active');10.

    });11.12.

    40.

    How to Toggle All the checkboxes on a page:

    view plain copy to clipboard print ?

    var tog = false; // or true if they are checked on load01.$('a').click(function() {02.

    $("input[type=checkbox]").attr("checked",!tog);03.tog = !tog;04.

    });05.

    41.

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

    view plain copy to clipboard print ?

    //If the value of the element matches that of the entered text01.//it will be returned02.

    $('.someClass').filter(function() {03. return $(this).attr('value') == $('input#someId').val() ;04.})05.

    42.

    How to get mouse cursor X and Y43.

    Query Snippets That Will Help You Become A Better JavaScript D... file:///C:/jq/50.ht

    r 11 05/01/2011 10:03

  • 8/8/2019 50 jQuery Snippets

    10/11

    view plain copy to clipboard print ?

    $(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.});06.

    How to make an entire List Element (LI) clickable

    view plain copy to clipboard print ?

    $("ul li").click(function(){01.

    window.location=$(this).find("a").attr("href"); returnfalse;02.});03.

    view plain copy to clipboard print ?

    01.

    Link 102.03.

    04. Link 205.06.07.

    Link 308.09.10.

    Link 411.12.

    13.

    44.

    How to Parse XML with jQuery (Basic example):

    view plain copy to clipboard print ?

    function parseXml(xml) {01. //find every Tutorial and print the author02.

    $(xml).find("Tutorial").each(function()03.{04.

    $("#output").append($(this).attr("author") + "");05.});06.

    }07.

    45.

    How to Check if an image has been fully loaded:

    view plain copy to clipboard print ?

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

    46.

    How to namespace events using jQuery:

    view plain copy to clipboard print ?

    //Events can be namespaced like this01.

    $('input').bind('blur.validation', function(e){02.

    // ...03. });04.05.//The data method also accept namespaces06.

    $('input').data('validation.isValid', true);07.

    47.

    Query Snippets That Will Help You Become A Better JavaScript D... file:///C:/jq/50.ht

    ur 11 05/01/2011 10:03

  • 8/8/2019 50 jQuery Snippets

    11/11

    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 enabled07.}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.

    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,'$1)05.

    );06.});07.

    return $(this);08. }09.10.

    //usage11.12.

    $('p').replaceUrl();13.

    50.

    Query Snippets That Will Help You Become A Better JavaScript D... file:///C:/jq/50.ht