12 Handy jQuery Snippets for Developers Week #2
Today we’ve collected 12 handy jQuery Snippets for developers of designers. Recently we look at 10 Popular Code Snippets for Developers Week #1 and showcase some CSS3 Snippets. In this list with found some cool and useful jQuery Snippets. Â If you’re in the web design industry, you know that jQuery is one of those fast growing tools.
jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML. It was released in January 2006 at BarCamp NYC by John Resig and was influenced by Dean Edwards’ earlier cssQuery library. It is currently developed by a team of developers led by Dave Methvin. Used by over 60% of the 10,000 most visited websites, jQuery is the most popular JavaScript library in use today.
These jQuery Snippets are for everyone to use, whether you’re a newbie or a pro, you’ll want to keep using these snippets for your work! To keep up to date with all the cool links, simply follow us @BloomWebDesign, Facebook and Subscribe via RSS.
Stay on top navigation toolbar when scrolling down
This is a navigation toolbar that will stay on top when you scroll down. It’s done with jquery. The logic is simple, when the length of the scrolled window is bigger than the position of the toolbar position, then I add a fixed class to the toolbar. If not then I remove it.
$(function(){ var $win = $(window) var $nav = $('.mytoolbar'); var navTop = $('.mytoolbar').length && $('.mytoolbar').offset().top; var isFixed=0; processScroll() $win.on('scroll', processScroll) function processScroll() { var i, scrollTop = $win.scrollTop() if (scrollTop >= navTop && !isFixed) { isFixed = 1 $nav.addClass('subnav-fixed') } else if (scrollTop <= navTop && isFixed) { isFixed = 0 $nav.removeClass('subnav-fixed') } } });
Simple Tabs
$(document).ready(function() { $('.tabs').each(function() { var $tabs = $(this), $toggles = $tabs.children('ul').find('li'), $tab = $tabs.find('.tab');
$toggles.eq(0).addClass('active'); $tab.eq(0).addClass('active');
$toggles.on('click', function() { var $this = $(this), index = $this.index();
if(!$this.hasClass('active')) { $toggles.removeClass('active'); $this.addClass('active');
$tab.hide(); $tab.eq(index).fadeIn(200); }
}); }); });
Gallery with touch and drag gestures
// disable the dragging of images on desktop browsers $("#slideshow img").bind("dragstart", function() { return false; });
/** * super simple slideshow * animation between slides happens with css transitions */ function Slideshow(container, overview) { container = $(container); overview = $(overview);
var slides = $(">li", container); var width = container.parent().width();
var self = this; var current = 0; var total_slides = slides.length;
// overview dots overview.click(function(ev) { self.slideTo( $(this).index() ); ev.preventDefault(); });
this.updateOverview = function() { overview.removeClass("active"); $(overview.get( current )).addClass('active'); } self.updateOverview();
// slide to given index this.slideTo = function( index ) { if(index > total_slides-1) { index = total_slides-1; } else if(index < 0) { index = 0; }
if(index == current) { return false; }
container.css({ left: 0 - (width * index) }); current = index;
self.updateOverview();
return true; };
this.next = function() { return this.slideTo(current+1); }
this.prev = function() { return this.slideTo(current-1); }
this.getContainer = function() { return container; }
this.getCurrent = function() { return $(slides.get(current)); } }
var hammer = new Hammer("#slideshow"); var slideshow = new Slideshow("#slideshow ul", "#overview li");
// ondrag we preview the next/prev slide hammer.ondrag = function(ev) { var left = 0;
// determine which direction we need to show the preview if(ev.direction == 'left') { left = 0 - ev.distance; } else if(ev.direction == 'right') { left = ev.distance; }
// just move the marginLeft slideshow.getContainer().css({ marginLeft: left }); };
// ondragend we will move to the next/prev slide when we have // opened it more then 100px on the screen hammer.ondragend = function(ev) { // restore the margin slideshow.getContainer().css({ marginLeft: 0 });
// if we moved the slide 100px then navigate if(Math.abs(ev.distance) > 100) { if(ev.direction == 'right') { slideshow.prev(); } else if(ev.direction == 'left') { slideshow.next(); } } };
Validate Dropdown
Force the user to make a selection from the dropdown menu. Submit button will be disabled until they make a selection.
$(document).ready(function() { formButton = $('div.service-form form button');
$(formButton).attr('disabled',''); $('#swcwidget_53_6').on('change', function(){ var currentText = $('#swcwidget_53_6 option:selected').text(); console.log('change!'); if(currentText == 'Please Select') { $(formButton).attr('disabled',''); } else { $(formButton).removeAttr('disabled'); } }); });
Open all external links in a new window
$('a').each(function() { // The link's href var theHref = $(this).attr('href').toLowerCase(); // The current domain var currentDomain = window.location.host; // Kill any subdomains var noSubDomain = currentDomain.match(/[^.]*.[^.]*$/)[0]; // Create a new (case insensitive) regex from the clean domain var theDomain = new RegExp(noSubDomain, 'gi');
if(/^https?/gi.test(theHref)) { // This link is using HTTP/HTTPs and is probably external if(theDomain.test(theHref)) { // Do nothing. For some reason, this site is using absolute internal links } else { $(this).attr('target', '_blank'); } } });
Jquery Drop-down Navigation on Mouse over
$(document).ready(function () {  $('#nav li').hover(  function () {  //show its submenu  //$('ul', this).slideDown(100);  $(this).children('ul').slideDown(100);  },  function () {  //hide its submenu  $(this).children('ul').slideUp(100);  }  );  });
jQuery URL Parameters
(function($) { $.QueryString = (function(a) { if (a == "") return {}; var b = {}; for (var i = 0; i < a.length; ++i) { var p=a[i].split('='); if (p.length != 2) continue; b[p[0]] = decodeURIComponent(p[1].replace(/+/g, " ")); } return b; })(window.location.search.substr(1).split('&')) })(jQuery);
//USAGE $.QueryString["MyParam"]
Simple Tooltip on jQuery
$.fn.tooltip = function(showTime, hideTime) { if(typeof showTime === "undefined") showTime = 200; if(typeof hideTime === "undefined") hideTime = 200; var $this = $(this); $this.hover(function() { var offsetLeft = parseInt($this.offset().left); offsetTop = parseInt($this.offset().top), text = $this.attr('title');
$this.removeAttr('title'); $('body').append('<div class="tooltip">'+text+'</div>'); $('.tooltip').css({ left: offsetLeft-$('.tooltip').width()/2, top: offsetTop-$('.tooltip').outerHeight()-15 }).animate({ opacity: 1, top: offsetTop-$('.tooltip').outerHeight()-10 }, showTime); }, function() { $(this).attr('title', text); $('.tooltip').animate({ opacity: 0, top: offsetTop-$('.tooltip').outerHeight()-15 }, hideTime, function() { $(this).remove(); }); }); }; // Example: // $('.tt[title]').tooltip(200,200);
jQuery Image Rotator with Links
function theRotator() { //Set the opacity of all images to 0 $('div.rotator ul li').css({opacity: 0.0}); //Get the first image and display it (gets set to full opacity) $('div.rotator ul li:first').css({opacity: 1.0}); //Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds setInterval('rotate()',6000); }
function rotate() { //Get the first image var current = ($('div.rotator ul li.show')? $('div.rotator ul li.show') : $('div.rotator ul li:first'));
if ( current.length == 0 ) current = $('div.rotator ul li:first');
//Get next image, when it reaches the end, rotate it back to the first image var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div.rotator ul li:first') :current.next()) : $('div.rotator ul li:first')); //Un-comment the 3 lines below to get the images in random order //var sibs = current.siblings(); //var rndNum = Math.floor(Math.random() * sibs.length ); //var next = $( sibs[ rndNum ] );
//Set the fade in effect for the next image, the show class has higher z-index next.css({opacity: 0.0}) .addClass('show') .animate({opacity: 1.0}, 1000);
//Hide the current image current.animate({opacity: 0.0}, 1000) .removeClass('show'); };
$(document).ready(function() { //Load the slideshow theRotator(); $('div.rotator').fadeIn(1000); $('div.rotator ul li').fadeIn(1000); // tweek for IE });
Automatically Add Lightbox Class
Add lightbox class (whatever CSS class you are using to identify your lightbox images) to all content images, but only those that link to images.
$('div.entry-content a img').each(function() { // The href of the link var theImageLink = $(this).parent("a").attr("href"); // The link itself var theParent = $(this).parent("a");
// Test the link to see if it's actually an image if ( !/.(jpg|jpeg|gif|png)$/i.test(theImageLink) ) { // This isn't an image link, follow the href } else { $(theParent).addClass('lbimage'); } });
JQuery Color Changer quick-function
function elementColorChange (element, newColor, originalColor, newFontColor, originalFontColor) { $(element).hover(function() { $(this).stop(true, true).animate ({ backgroundColor: newColor, color: newFontColor
}, 200) }, function (){ $(this).stop(true, true).animate ({ backgroundColor: originalColor, color: originalFontColor }, 200) }); }
Jquery infinite scroll using AJAX
function lastPostFunc() { $('div#lastPostsLoader').html('<img src="bigLoader.gif">');
var lastItemId = parseInt($(".wrdLatest:last").attr("id")); if (isNaN(lastItemId)) { return; }
var data = "lastItemId=" + lastItemId;
$.ajax({ type: "post", url: "/getItems", cache: false, data: data, success: function(json){ $(".wrdLatest:last").after(html); $('div#lastPostsLoader').empty(); }, error: function(response) { alert(response.responseText); } }); }
$(window).scroll(function(){ if ($(window).scrollTop() == $(document).height() - $(window).height()){ lastPostFunc(); } });