10 jQuery snippets for efficient web development

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

Leave a Reply

Your email address will not be published. Required fields are marked *