Some Useful JavaScript & jQuery Snippets

How to refresh the src of an image with jQuery? $(imageobj).attr(‘src’, $(imageobj) .attr(‘src’) + ‘?’ + Math.random() ); How to see if an image is loaded or not with jquery […]

  • How to refresh the src of an image with jQuery?
  • $(imageobj).attr('src', $(imageobj)
               .attr('src') + '?' + Math.random() );
  • How to see if an image is loaded or not with jquery
  • var imgsrc = 'img/image1.png';
    $('<img/>').load(function () {
        alert('image loaded');
    }).error(function () {
        alert('error loading image');
    }).attr('src', imgsrc);
  • And if a set (example : 10 images) of images are loaded
  • var totalimages  = 10;
    var loadedimages = 0;
    $("<img/>").load(function() {
        ++loadedimages;
        if(loadedimages == totalimages){
            //All 10 images are loaded
        }
    });
  • How to remove selected text after mouse double click event
  • clearSelection      : function () {
        if(document.selection && document.selection.empty) {
            document.selection.empty();
        } else if(window.getSelection) {
            var sel = window.getSelection();
            sel.removeAllRanges();
        }
    }
    $(element).bind('dblclick',function(event){
        //do something
        clearSelection();
    });

    Tiny break: 📬 Want to stay up to date with frontend and trends in web design? Subscribe and get our Collective newsletter twice a tweek.

  • Validate email address:
  • var email = 'info@tympanus.net'
    if(!(/^((([a-z]|d|[!#$%&'*+-/=?^_`{|}~]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])+(.([a-z]|d|[!#$%&'*+-/=?^_`{|}~]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])+)*)|((x22)((((x20|x09)*(x0dx0a))?(x20|x09)+)?(([x01-x08x0bx0cx0e-x1fx7f]|x21|[x23-x5b]|[x5d-x7e]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(\([x01-x09x0bx0cx0d-x7f]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))))*(((x20|x09)*(x0dx0a))?(x20|x09)+)?(x22)))@((([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|d|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).)+(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])|(([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])([a-z]|d|-|.|_|~|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF])*([a-z]|[u00A0-uD7FFuF900-uFDCFuFDF0-uFFEF]))).?$/i.test(email)))
    alert('Invalid Email');
  • How to order a <ul> element using jQuery
  • <ul>
    <li>cloud</li>
    <li>sun</li>
    <li>rain</li>
    <li>snow</li>
    </ul
    
    var items = $('.to_order li').get();
    items.sort(function(a,b){
        var keyA = $(a).text();
        var keyB = $(b).text();
    
        if (keyA < keyB) return -1;
        if (keyA > keyB) return 1;
        return 0;
    });
    var ul = $('.to_order');
    $.each(items, function(i, li){
        ul.append(li);
    });
  • Passing parameters to a function called with setTimeout
  • timeout = setTimeout(function(){myFunction(param)},time);
  • Disable right mouse click
  • $(document).ready(function(){
        $(document).bind("contextmenu",function(e){
            return false;
        });
    });
  • Fade out an image, and fade in another one (replacing the previous one)
  • $('imageelement').fadeOut(function() {
        $(this).load(function() {
            $(this).fadeIn();
        }).attr('src', AnotherSource);
    });
  • Write your own selectors
  • //extend the jQuery functionality
    $.extend($.expr[':'], {
    
        //name of your special selector
        moreThanAThousand : function (a){
            //Matching element
            return parseInt($(a).html()) > 1000;
        }
    });
    
    $(document).ready(function() {
        $('td:moreThanAThousand').css('background-color', '#ff0000');
    });
  • Run a function 5 times with intervals of 20 seconds
  • var count = 0;
    function myFunction() {
        count++;
        if(count > 5) clearInterval(timeout);
        //do something
    }
    var timeout = setInterval(myFunction, 20000);
  • Check if an element exists
  • if ($("#elementid").length) {
        //it does!
    }
  • Cancel an ajax request
  • var req = $.ajax({
    type:     "POST",
    url:     "someurl",
    data:     "id=1",
    success: function(){
    //something
    }
    });
    //Cancel the Ajax Request
    req.abort()

    Message from TestkingIf want to learn how to use javascript and JQuery to create powerful websites then join testking 70-647 online designing course and get expert testking 350-018 reviews and and testking 640-553 tutorials to learn how to create effective web lauouts.

    cody

    Cody loves jQuery - he puts the magic into every web application. He is crazy about Curry dishes.

    Stay in the loop: Get your dose of frontend twice a week

    Fresh news, inspo, code demos, and UI animations—zero fluff, all quality. Make your Mondays and Thursdays creative!

    Feedback 18

    Comments are closed.
    1. Pingback: Some Useful JavaScript & jQuery Snippets | Codrops

    2. Pingback: Some Useful JavaScript & jQuery Snippets | Codrops « Netcrema – creme de la social news via digg + delicious + stumpleupon + reddit

    3. Pingback: Some Useful JavaScript & jQuery Snippets - Part 2 | Codrops

    4. Pingback: Some Useful JavaScript & jQuery Snippets | Codrops : Popular Links : eConsultant

    5. Pingback: Some Useful JavaScript & jQuery Snippets - Part 3 | Codrops

    6. Pingback: Some Useful JavaScript & jQuery Snippets | Codrops » Web Design

    7. Pingback: links for 2010-01-08 | Digital Rehab

    8. Pingback: jQuery et Javascript : quelques snippets utiles

    9. Pingback: Astuces (Snippets) pratiques pour Javascript et jQuery » Javascript & Web Design - Tous les jours le meilleur des ressources Javascript pour intégrateurs web front-end (avec parfois un soupçon de PHP)

    10. Pingback: 2010/01/09???????? | debeso

    11. Pingback: Snippets de Javascript y jQuery para ahorrar tiempo - elWebmaster.com

    12. Pingback: IT???? | 2009?12/27?2010?1/9?????????

    13. Pingback: links for 2010-01-11 « 2LeggedSpider

    14. Pingback: ??????? » [Web] ????

    15. Pingback: links for 2010-01-17 « Web????????? Web??????????? S5-Style