850-417-7698 support@omegaweb.com

jQuery became an essential part of any web project. It provides interactivity to websites by moving HTML elements around, creating custom animations, handling events, selecting DOM elements, navigating a document that offers a better end user experience to visitors. The modular approach to the jQuery library also allows the creation of powerful dynamic web pages and web applications.

In this article I have collected 20+ reusable jQuery code snippets which you may easily copy and paste directly into your websites to create awesome effects.

Reusable jQuery Code Snippets for Developers

Lazy loading of Images

jQuery(document).ready(function() {
    jQuery("img.lazy").lazy({
        delay: 2000
    });
});

Source

Preloading of Images

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

Source

Partial Page Refresh

setInterval(function() {
	$("#refresh").load(location.href+" #refresh>*","");
}, 10000);

Source

Delay Animation/Effect

$(".alert").delay(2000).fadeOut();

Source

Open external link in New Window

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if(!a.test(this.href)) {
       $(this).click(function(event) {
           event.preventDefault();
           event.stopPropagation();
           window.open(this.href, '_blank');
       });
   }
});

Source

Make Everything Mobile Friendly

var scr = document.createElement('script');
scr.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/
jquery.min.js');
document.body.appendChild(scr);

scr.onload = function(){

	$('div').attr('class', '').attr('id', '').css({
		'margin' : 0,
		'padding' : 0,
		'width': '100%',
		'clear':'both'
	});
};

Source

Image Resize Using jQuery

$(window).bind("load", function() {
	// IMAGE RESIZE
	$('#product_cat_list img').each(function() {
		var maxWidth = 120;
		var maxHeight = 120;
		var ratio = 0;
		var width = $(this).width();
		var height = $(this).height();

		if(width > maxWidth){
			ratio = maxWidth / width;
			$(this).css("width", maxWidth);
			$(this).css("height", height * ratio);
			height = height * ratio;
		}
		var width = $(this).width();
		var height = $(this).height();
		if(height > maxHeight){
			ratio = maxHeight / height;
			$(this).css("height", maxHeight);
			$(this).css("width", width * ratio);
			width = width * ratio;
		}
	});
	//$("#contentpage img").show();
	// IMAGE RESIZE
});

Source

Smooth Scrolling

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
 && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

Source

Window load event with minimum delay

(function fn() {

  fn.now = +new Date;

  $(window).load(function() {

     if (+new Date - fn.now < 500) setTimeout(fn, 500);

		 // Do something

  });

})();

Source

jQuery Accordion

(function($) {

  var allPanels = $('.accordion > dd').hide();

  $('.accordion > dt > a').click(function() {
    allPanels.slideUp();
    $(this).parent().next().slideDown();
    return false;
  });

})(jQuery);

Source

Simple Auto-Playing Slideshow

$("#slideshow > div:gt(0)").hide();

setInterval(function() { 
  $('#slideshow > div:first')
    .fadeOut(1000)
    .next()
    .fadeIn(1000)
    .end()
    .appendTo('#slideshow');
},  3000);

Source

Shuffle DOM Elements

(function($){

    $.fn.shuffle = function() {

        var allElems = this.get(),
            getRandom = function(max) {
                return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function(){
                var random = getRandom(allElems.length),
                    randEl = $(allElems[random]).clone(true)[0];
                allElems.splice(random, 1);
                return randEl;
           });

        this.each(function(i){
            $(this).replaceWith($(shuffled[i]));
        });

        return $(shuffled);

    };

})(jQuery);

Source

Scroll Page Horizontally With Mouse Wheel

$(function() {

   $("body").mousewheel(function(event, delta) {

      this.scrollLeft -= (delta * 30);

      event.preventDefault();

   });

});

Source

Load Only a Section of a Page

$("#mainNav").load("/store #mainNav")

Source

Highlight Related Label when Input in Focus

$("form :input").focus(function() {
  $("label[for='" + this.id + "']").addClass("labelfocus");
}).blur(function() {
  $("label").removeClass("labelfocus");
});

Source

Highlight All Links To Current Page

$(function(){
	$("a").each(function(){
	   if ($(this).attr("href") == window.location.pathname){
			$(this).addClass("selected");
	   }
	});
});

Source

Better Broken Image Handling

// Replace source
$('img').error(function(){
        $(this).attr('src', 'missing.png');
});

// Or, hide them
$("img").error(function(){
        $(this).hide();
});

Source

Load Content on Scroll Automatically

var loading = false;
$(window).scroll(function(){
	if((($(window).scrollTop()+$(window).height())+250)>=$(document).
height()){
		if(loading == false){
			loading = true;
			$('#loadingbar').css("display","block");
			$.get("load.php?start="+$('#loaded_max').val(), 
function(loaded){
				$('body').append(loaded);
				$('#loaded_max').val(parseInt($('#loaded_max')
.val())+50);
				$('#loadingbar').css("display","none");
				loading = false;
			});
		}
	}
});

$(document).ready(function() {
	$('#loaded_max').val(50);
});

Source

Prevent Multiple Submit of Your Form

$(document).ready(function() {
  $('form').submit(function() {
    if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
      jQuery.data(this, "disabledOnSubmit", { submited: true });
      $('input[type=submit], input[type=button]', this).each(function() {
        $(this).attr("disabled", "disabled");
      });
      return true;
    }
    else
    {
      return false;
    }
  });
});

Source

Make Entire Div Clickable

$(".myBox").click(function(){
     window.location=$(this).find("a").attr("href"); 
     return false;
});

Source

Toggle Text

$("#more-less-options-button").click(function() {
     var txt = $("#extra-options").is(':visible') ? 'more options' : 'less 
options';
     $("#more-less-options-button").text(txt);
     $("#extra-options").slideToggle();
});

Source

 

email