10 jQuery snippets for efficient web development

10 jQuery snippets for efficient web development

Amongst the years, jQuery has became the most widely used JavaScript library. Today, here is a showcase of 10 super useful jQuery snippets that every developer should have saved somewhere for future use.


Detect Internet Explorer

When it comes to CSS design, Internet Explorer has always been a problem for developpers and designers. Althought the dark ages of IE6 are now gone and IE is les and less popular, it still a good thing to be able to detect it easily. Of course, this snippet can be used to detect other browsers as well.

$(document).ready(function() {
      if (navigator.userAgent.match(/msie/i) ){
        alert('I am an old fashioned Internet Explorer');
      }
});

Source: Stack Overflow

Smooth scrolling to top of the page

Here is one of the most widely used jQuery effects: a click on a link will smoothly scroll the page to the top. Nothing new here, but a must have as every developer will have to code similar functions every once in a while.

$("a[href='#top']").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});

Source: Stalk Overflow

Stay on top

A very handy code snippets which allows an element to stay fixed on top. Super useful for navigation menus, toolbars or important messages.

$(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')
	}
}

Source: DesignBump

Replace html tag by another

jQuery makes it super easy to replace a html tag by another. The possibilities are then endless.

$('li').replaceWith(function(){
  return $("<div />").append($(this).contents());
});

Source: Allure Web Solutions

Detect viewport width

Now that mobiles dvices are even more popular than old-fashioned computers, it’s super usefull to be able to easily detect a smaller viewport. Fortunately, it’s supêr easy to do with jQuery.

var responsive_viewport = $(window).width();

/* if is below 481px */
if (responsive_viewport < 481) {
    alert('Viewport is smaller than 481px.');
} /* end smallest screen */

Source: jQuery Rain

Automatically fix broken images

If your site is big and have been online for a couple of years, you're always more or less at risk of having broken images somewhere. This useful function detects broken images and replace it with an image of your choice, noticing visitors about the problem.

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

Source: WebDesignerDepot

Detect Copy, Paste and Cut Behavior

Using jQuery, it's super easy to detect copy, paste and cut behaviors on an element of your choice.

$("#textA").bind('copy', function() {
    $('span').text('copy behaviour detected!')
}); 
$("#textA").bind('paste', function() {
    $('span').text('paste behaviour detected!')
}); 
$("#textA").bind('cut', function() {
    $('span').text('cut behaviour detected!')
});

Source: Snipplr

Automatic target="blank" attribute to external links

When linking to an external site, you might want to use the target="blank" attribute in order to open that site in a new tab. The problem is that the target="blank" attribute isn't W3C valid. Let's get jQuery to the rescue: this little snippet will detect if the link is external, and if yes, will automatically add a target="blank" attribute to it.

var root = location.protocol + '//' + location.host;
$('a').not(':contains(root)').click(function(){
    this.target = "_blank";
});

Source: jQuery Rain

Fade In/Out on Hover

Another "classic" snippet to have in your toolbox, as you'll have to implement it every now and then.

$(document).ready(function(){
    $(".thumbs img").fadeTo("slow", 0.6); // This sets the opacity of the thumbs to fade down to 60% when the page loads

    $(".thumbs img").hover(function(){
        $(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover
    },function(){
        $(this).fadeTo("slow", 0.6); // This should set the opacity back to 60% on mouseout
    });
});

Source: Snipplr

disable space in text/password inputs

Spaces aren't needed in many form fields, like email, username, password, etc. Here's a very simple trick to disable spaces on selected inputs.

$('input.nospace').keydown(function(e) {
	if (e.keyCode == 32) {
		return false;
	}
});

Source: Queness

Enjoyed this article? Please consider donating: 3FVR5qaxYV8yAgNUUS7FC3o8c54YfDR5zK
  • I’ve had mixed experiences with $(window).width();, given the variety of scroll bar widths. This is what I use now:

    var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], x;

    x = w.innerWidth || e.clientWidth || g.clientWidth; // x will equal a more accurate viewport width

    I know it’s not jQuery but I see it as a choice between ease and accuracy. I’ll take accuracy every time.