8 Handy jQuery Code Snippets For Your Next Project


Here are 8 handy jQuery code snippets for your next project. These jQuery code snippets are super handy and can make your life easy for handling small things efficiently. These snippets allow you to handle css, jQuery animations, deal with input boxes and calculate the page load time.
1. Remove all inline styles using jQuery
$(document).ready(function(){
   $("* [style]").removeAttr("style");
})

2. Disable jQuery animation
You can disable the jQuery animation via setting fx.off property.
$(document).ready(function() {
   jQuery.fx.off = true;
});

3. Select all readonly input type textbox
$(document).ready(function() {
  $(":input[type=text][readonly='readonly']").val("");
});

4. Disable double click event
$(document).ready(function() {
   $("*").dblclick(function(e){
     e.preventDefault();
   });
});

5. Clear textbox value using ESC key
$(document).ready(function() {
    $('input[type="text"]').keyup(function(e){
        if(e.keyCode == 27) {
            $(this).val('');
        }
    });
});

6. Load CSS files using jQuery
For if you wish to load CSS files dynamically based on certain conditions
$(document).ready(function(){
   $("head").append("<link>");
var css = $("head").children(":last");
css.attr({
    rel:  "stylesheet",
    type: "text/css",
    href: "CSS/Demo.css"
  });
});

7. Calculate page load time using jQuery
var startTime = (new Date()).getTime();
function CalculatePageLoadTime(){
   var endTime = (new Date()).getTime();
   var diff = (endTime-startTime) / 1000;
   console.log('Page load time: ' + diff + ' sec(s).');
}
window.onload = CalculatePageLoadTime;

8. Check if HTML element is empty
function isElementEmpty(elm){
    return !$.trim(elm.html())
}
if (isElementEmpty($('#element'))) {
    //do something
}
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..