Efficient and Helpful JavaScript/jQuery Tips and Tricks

This free HTML JavaScript tutorial provides 45+ JavaScript/jQuery tips and tricks that help you work in JavaScript tasks better, through live HTML JavaScript example codes. List of some JavaScript tips and tricks:

- Refreshing the src of an image with jQuery?
- Check if an image is loaded or not with jQuery
- Remove selected text after mouse double click JavaScript event
- Validate an email address
- Check if an HTML control element exists
- Cancel an AJAX request
- Select all HTML checkboxes
- Selecting root element of a certain level in the document
- Searching a string in jQuery

Please go to the full post page for full detailed tips and HTML JavaScript example codes, then try some JavaScript tutorials:

- 10 Small Javascript Tricks You Should Master
- Some Basic Tips and Tricks for Speeding Up JavaScript
- 10 jQuery and JavaScript Tips and Tricks to Improve Your Code
- 5 Good and Small JavaScript Tips and Tricks


Sampled by © JavaScriptBank.com

  • How to refresh the src of an image with jQuery?
  • 1.$(imageobj).attr('src', $(imageobj)
    2.           .attr('src') + '?' + Math.random() );
  • How to see if an image is loaded or not with jquery
  • 1.var imgsrc = 'img/image1.png';
    2.$('<img/>').load(function () {
    3.    alert('image loaded');
    4.}).error(function () {
    5.    alert('error loading image');
    6.}).attr('src', imgsrc);
  • And if a set (example : 10 images) of images are loaded
  • 1.var totalimages  = 10;
    2.var loadedimages = 0;
    3.$("<img/>").load(function() {
    4.    ++loadedimages;
    5.    if(loadedimages == totalimages){
    6.        //All 10 images are loaded
    7.    }
    8.});
  • How to remove selected text after mouse double click event
  • 01.clearSelection      : function () {
    02.    if(document.selection && document.selection.empty) {
    03.        document.selection.empty();
    04.    } else if(window.getSelection) {
    05.        var sel = window.getSelection();
    06.        sel.removeAllRanges();
    07.    }
    08.}
    09.$(element).bind('dblclick',function(event){
    10.    //do something
    11.    clearSelection();
    12.});
  • Validate email address:
  • 1.var email = 'info@tympanus.net'
    2.if(!(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email)))
    3.alert('Invalid Email');
  • How to order a <ul> element using jQuery
  • 01.<ul>
    02.<li>cloud</li>
    03.<li>sun</li>
    04.<li>rain</li>
    05.<li>snow</li>
    06.</ul
    07. 
    08.var items = $('.to_order li').get();
    09.items.sort(function(a,b){
    10.    var keyA = $(a).text();
    11.    var keyB = $(b).text();
    12. 
    13.    if (keyA < keyB) return -1;
    14.    if (keyA > keyB) return 1;
    15.    return 0;
    16.});
    17.var ul = $('.to_order');
    18.$.each(items, function(i, li){
    19.    ul.append(li);
    20.});
  • Passing parameters to a function called with setTimeout
  • 1.timeout = setTimeout(function(){myFunction(param)},time);
  • Disable right mouse click
  • 1.$(document).ready(function(){
    2.    $(document).bind("contextmenu",function(e){
    3.        return false;
    4.    });
    5.});
  • Fade out an image, and fade in another one (replacing the previous one)
  • 1.$('imageelement').fadeOut(function() {
    2.    $(this).load(function() {
    3.        $(this).fadeIn();
    4.    }).attr('src', AnotherSource);
    5.});
  • Write your own selectors
  • 01.//extend the jQuery functionality
    02.$.extend($.expr[':'], {
    03. 
    04.    //name of your special selector
    05.    moreThanAThousand : function (a){
    06.        //Matching element
    07.        return parseInt($(a).html()) > 1000;
    08.    }
    09.});
    10. 
    11.$(document).ready(function() {
    12.    $('td:moreThanAThousand').css('background-color', '#ff0000');
    13.});
  • Run a function 5 times with intervals of 20 seconds
  • 1.var count = 0;
    2.function myFunction() {
    3.    count++;
    4.    if(count > 5) clearInterval(timeout);
    5.    //do something
    6.}
    7.var timeout = setInterval(myFunction, 20000);
  • Check if an element exists
  • 1.if ($("#elementid").length) {
    2.    //it does!
    3.}
  • Cancel an ajax request
  • 01.var req = $.ajax({
    02.type:     "POST",
    03.url:     "someurl",
    04.data:     "id=1",
    05.success: function(){
    06.//something
    07.}
    08.});
    09.//Cancel the Ajax Request
    10.req.abort()
  • Check if cookies are enabled
  • 01.$(document).ready(function() {
    02.    var dt = new Date();
    03.    dt.setSeconds(dt.getSeconds() + 60);
    04.    document.cookie = "cookietest=1; expires=" + dt.toGMTString();
    05.    var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
    06.    if(!cookiesEnabled){
    07.        //cookies are not enabled
    08.    }
    09.});
  • Toggle all checkboxes
  • 1.var tog = false; // or true if they are checked on load
    2.$('a').click(function() {
    3.    $("input[type=checkbox]").attr("checked",!tog);
    4.    tog = !tog;
    5.});
  • Get the index of an element
  • 1.$("ul > li").click(function () {
    2.    var index = $(this).prevAll().length;
    3.});
  • Validate date of birth
  • 01.$("#lda-form").submit(function(){
    02.    var day = $("#day").val();
    03.    var month = $("#month").val();
    04.    var year = $("#year").val();
    05.    var age = 18;
    06.    var mydate = new Date();
    07.    mydate.setFullYear(year, month-1, day);
    08. 
    09.    var currdate = new Date();
    10.    currdate.setFullYear(currdate.getFullYear() - age);
    11.    if ((currdate - mydate) < 0){
    12.        alert("Sorry, only persons over the age of " + age + " may enter this site");
    13.        return false;
    14.    }
    15.    return true;
    16.});
  • Test if an element is visible
  • 1.if($(element).is(":visible")) {
    2.    //The element is Visible
    3.}
  • Counting child elements
  • 01.<div id="foo">
    02.<div id="bar"></div>
    03.<div id="baz">
    04.<div id="biz">
    05.</div>
    06.<span><span>
    07.</div>
    08. 
    09.//jQuery code to count child elements
    10.$("#foo > div").length
  • Center an element on the screen
  • 01.jQuery.fn.center = function () {
    02.    this.css("position","absolute");
    03.    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    04.    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    05.    return this;
    06.}
    07. 
    08.//Use the above function as:
    09.$(element).center();
  • Moving options from list A to list B
  • 1.$().ready(function() {
    2.    $('#add').click(function() {
    3.        !$('#select1 option:selected').appendTo('#select2');
    4.    });
    5.    $('#remove').click(function() {
    6.        !$('#select2 option:selected').appendTo('#select1');
    7.    });
    8.});
  • Select all checkboxes
  • 1.$(document).ready(function(){
    2.    $("#checkboxall").change(function(){
    3.        var checked_status = this.checked;
    4.        $("input[name=checkall]").attr("checked", checked_status);
    5.    });
    6. 
    7.});
  • Get the current URL
  • 1.$(document).ready(function() {
    2.    var pathname = window.location.pathname;
    3.});
  • Check if and which key was pressed
  • 01.$(function() {
    02.    $(document).keypress(function(e){
    03.        switch(e.which){
    04.        // "ENTER"
    05.        case 13:
    06.        alert('enter pressed');
    07.        break;
    08. 
    09.        // "s"
    10.        case 115:
    11.        alert('s pressed');
    12.        break;
    13. 
    14.        (...)
    15. 
    16.        }
    17.    });
    18. 
    19.});
  • How to hide all children div except a specific one with jQuery?
  • 1.$('#target div:not(#exclude)').hide();
    2.//or
    3.$('#target').children().filter(':not(#exclude)').hide();
  • Detecting when a div's height changes using jQuery
  • 1.$('element').bind('resize', function(){
    2.alert( 'Height changed to' + $(this).height() );
    3.}
  • Delete all table rows except first
  • 1.$('someTableSelector').find('tr:gt(0)').remove();
  • Selecting root element of a certain level in the document
  • 1.1 level:
    2.$('*:not(* *)');
    3.2 level:
    4.$('*:not(* *)').find('> *');
    5.3 level:
    6.$('*:not(* *)').find('> * > *');
  • Searching a string in jQuery
  • 1.var foundin = $('*:contains("some string bla bla")');
  • Get the distance scrolled from top
  • 1.alert($(document).scrollTop());
  • Select all elements except the ones with a given class
  • 1.$('* :not(.someclass)')
  • Add a row to a table
  • 1.$('#myTable tr:last').after('<tr>...</tr>');
  • How to convert decimal to hexadecimal?
  • 1.num = num.toString(16);
    2.reverse process:
    3.num = parseInt(num, 16);
  • Filtering By More Than One Attribute in JQuery
  • 1.var elements = $('#someid input[type=sometype][value=somevalue]').get();
  • How to expire a cookie in x minutes
  • 1.var date = new Date();
    2.date.setTime(date.getTime() + (x * 60 * 1000));
    3.$.cookie('example', 'foo', { expires: date });
  • Selecting the first x items with jQuery
  • 1.example: first 10 anchors
    2.$('a').slice(0,10);
    3.//or
    4.$('a:lt(10)');
  • Working with a select element
  • 1.//Get the value of a selected option
    2.$('selectElement').val();
    3. 
    4.//Get the text of a selected option
    5.$('#selectElementId :selected').text();
    6. 
    7.//Remove an option (e.g. id=1)
    8.$("#selectElementId option[value='1']").remove();
  • How to get client ip address with jQuery
  • 1.$.getJSON("http://jsonip.appspot.com?callback=?",function(data){
    2.    alert( "Your ip: " + data.ip);
    3.});
  • How to parse XML with jQuery
  • file.xml:

    01.<?xml version="1.0" ?>
    02.<result>
    03.    <item>
    04.        <id>1</id>
    05.        <title>title1</title>
    06.        <description>desc1</description>
    07.    </item>
    08.    <item>
    09.        <id>2</id>
    10.        <title>title2</title>
    11.        <description>desc2</description>
    12.    </item>
    13.    <!-- ... -->
    14.</result>
    01.$.get('file.xml',{},function(data){
    02.    $('item',data).each(function(){
    03.        var $this       = $(this);
    04.        var id             = $this.find('id').text();
    05.        var title         = $this.find('title').text();
    06.        var description = $this.find('description').text();
    07.        //do something ...
    08.    });
    09.});
  • How to get the number in the ids
  • 1.<div id="sites">
    2.    <a id="site_1" href="http://siteA.com">siteA</a>
    3.    <a id="site_2" href="http://siteB.com">siteB</a>
    4.    <a id="site_3" href="http://siteB.com">siteC</a>
    5.    ...
    6.</div>

    you need to get 1 from site_1, 2 from site_2 ...

    1.$("#sites a").click(function(){
    2.    var $this     = $(this);
    3.    var nmb     = $this.attr('id').match(/site_(\d+)/)[1];
    4.    ...
    5.});
  • How to transform a number like 12343778 into 12.343.778
  • 1.<div id="result">12343778</div>
    1.var delimiter = '.';
    2.$('#result').html()
    3.            .toString()
    4.            .replace(new RegExp("(^\\d{"+($this.html().toString().length%3||-1)+"})(?=\\d{3})"),"$1" + delimiter)
    5.            .replace(/(\d{3})(?=\d)/g,"$1" + delimiter);
  • Count number of textarea lines
  • 1.var text = $("#textareaId").val();
    2.var lines = text.split(/\r|\r\n|\n/);
    3.alert(lines.length);
  • Logging to the firebug console
  • 1.jQuery.fn.log = function (msg) {
    2.    console.log("%s: %o", msg, this);
    3.    return this;
    4.};
    5.$('#some_div').find('li.source > input:checkbox').log("sources to uncheck").removeAttr("checked");
  • Find X/Y of an HTML element with Javascript
  • 02.var getCumulativeOffset = function (obj) {
    03.    var left, top;
    04.    left = top = 0;
    05.    if (obj.offsetParent) {
    06.        do {
    07.            left += obj.offsetLeft;
    08.            top  += obj.offsetTop;
    09.        } while (obj = obj.offsetParent);
    10.    }
    11.    return {
    12.        x : left,
    13.        y : top
    14.    };
    15.};
  • Validate Credit Card
  • 01.function isCreditCard( CC ){
    02.    if (CC.length > 19)
    03.        return (false);
    04. 
    05.    sum = 0; mul = 1; l = CC.length;
    06.    for (i = 0; i < l; i++){
    07.        digit = CC.substring(l-i-1,l-i);
    08.        tproduct = parseInt(digit ,10)*mul;
    09.        if (tproduct >= 10)
    10.            sum += (tproduct % 10) + 1;
    11.        else
    12.            sum += tproduct;
    13.        if (mul == 1)
    14.            mul++;
    15.        else
    16.            mul-;
    17.    }
    18.    if ((sum % 10) == 0)
    19.        return (true);
    20.    else
    21.        return (false);
    22.}
  • Distinguish left and right mouse click
  • 1.$("#element").live('click', function(e) {
    2.    if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
    3.        alert("Left Button");
    4.    }
    5.    else if(e.button == 2)
    6.        alert("Right Button");
    7.});
  • How to get the native image size
  • 1.var img = $('#imageid');
    2.var theImage = new Image();
    3.theImage.src = img.attr("src");
    4.alert("Width: " + theImage.width);
    5.alert("Height: " + theImage.height);

    Language
    Translate this page to English Translate this page to French Translate this page to Vietnamese

    Recent articles
    How to open a car sharing service
    Vue developer as a vital part of every software team
    Vue.js developers: hire them, use them and get ahead of the competition
    3 Reasons Why Java is so Popular
    Migrate to Angular: why and how you should do it
    The Possible Working Methods of Python Ideology
    JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
    Learning How to Make Use of New Marketing Trends
    5 Important Elements of an E-commerce Website
    How To Create A Successful Prototype For Your PCB


    Top view articles
    Top 10 Beautiful Christmas Countdown Timers
    Adding JavaScript to WordPress Effectively with JavaScript Localization feature
    65 Free JavaScript Photo Gallery Solutions
    16 Free Code Syntax Highlighters by Javascript For Better Programming
    Best Free Linux Web Programming Editors
    Top 10 Best JavaScript eBooks that Beginners should Learn
    Top 50 Most Addictive and Popular Facebook mini games
    More 30 Excellent JavaScript/AJAX based Photo Galleries to Boost your Sites
    Top 10 Free Web Chat box Plug-ins and Add-ons
    The Ultimate JavaScript Tutorial in Web Design


    Free JavaScript Tutorials & Articles
    at www.JavaScriptBank.com