15 Must-Have jQuery Codes (AKA Snippets) To Add Vivacity to Your Website

Truth be told, JaveScript coding can be a ‘pain in the neck’ and not just sometimes but always. However, this has become a thing of the past now since the dawn of jQuery.

15 Must-Have jQuery Codes (AKA Snippets) To Add Vivacity to Your Website

jQuery is not a new language nor is it an independent platform, but a pre-written client-side script that harnesses the power of JavaScript Library. It is akin to a gift from heaven, especially, for front-end developers bestowed upon them only for one reason alone: ‘let there be code’.

As charming as it may sound, for someone who is just stepping into the web development field, it is important to at least have a basic knowledge of JavaScript. Otherwise, jQuery or no jQuery, getting one’s head around this script would always be a challenge.

Nevertheless, with just a single search on Google, you can easily get an infinite list of resources pointing to an infinite trove of jQuery snippets. But, finding the best ones that can speed-up the things on your end can be a bit hectic as well as time-consuming. To save you from this trouble, I’ve put together a list of some powerful jQuery snippets that are a ‘must’ for every developer.

1. Toggle Stylesheet
//Look for the media-type you wish to switch then set the href to your new style sheet
$('link[media='screen']').attr('href', 'Alternative.css');

Creating more than one stylesheet for a website is pretty common. Developers do this from time to time to make surfing convenient for visitors. For instance, some websites sport a pretty vibrant color scheme, which often seems irritating to some visitors. The best way to retain such visitors and give them a great user experience is to offer them an alternative stylesheet, say a simple black and white view, which can be done easily with this snippet.

2. Forbid Right-Click Menu
$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
});

Some web developers disable contextual right-click menu on their web pages. One common reason of doing that is to fend off image stealers. Regardless of the reason, you can bind the right-click menu using this simple snippet.

3. Disable/Re-enable Input Field

to Disable:

$('input[type="submit"]').attr("disabled", true);

to Re-enable

$('input[type="submit"]').removeAttr("disabled”);

Oftentimes, we disable particular fields that can only be enabled if the visitor checks or fills the previous fields. Take for instance a disabled submit button on a form, which can only be enabled if the visitors check the ‘I accept terms and conditions’ box. Use the aforementioned scripts to disable or re-enable the fields.

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

If you want to link an entire DIV element and make it clickable, this is the jQuery you should be using. When a user click anywhere on the DIV, the ‘myBox’ value will look the link into the DIV class of ‘myBox’ in the HTML source and redirects the user to the link mentioned therein.

5. Load External Content
$("#content").load("somefile.html", function(response, status, xhr) {
  // error handling
  if(status == "error") {
    $("#content").html("An error occured: " + xhr.status + " " + xhr.statusText);
  }
});

Loading external file from a server onto a webpage has never been so easy. Use this script to try it yourself and see the results.

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

It is a pretty common yet powerful snippet that makes scrolling way easier and faster for visitors. The plugin allows users to go back at the top of the page no matter where they are surfing on the page. For instance, if a user scrolled his way to the end of a long page, he can immediately go back to the top by clicking ‘scroll to top’ or ‘top’ button. You can find a nice example of this snippet on almost every social media site.

7. Sense Mobile Devices
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
	// Do something
} else {
	// Do something else
}

This cute little library is a must tool for every developer as it allows you to detect what mobile device the user is using to surf content on your web page. The use of this script has become commonly lately due to the excessive amount of responsive web designs on the Internet.

8. Open Pop-ups
jQuery('a.popup').live('click', function() {</pre>
 newwindow=window.open($(this).attr('href'),'','height=100,width=100');
  if(window.focus) {newwindow.focus()}
  return false;
});

There’s no better and effective way to increase conversion on your site than using eye-catching pop-ups. Although pop-ups can often be a bit annoying, they can be very productive if used stylishly. With the above script, you can easily open pop-ups on your pages.

9. Partial Page Refresh
setInterval(function() {
$("#refresh").load(location.href+" #refresh>*","");
}, 10000); // milliseconds to wait

At times, we only want to refresh a specific section of the web page to show new updates and keep the rest of the page as is. We do this by using the above script. You can see this script in action in almost every news portal in which news headlines need to be refreshed every few seconds.

10. Display Table Stripes
$(document).ready(function(){                             
     $("table tr:even").addClass('stripe');
});

Using a uniform color scheme for a pricing or features table seems monotonous to users. Consequently, it might result in low conversions. The best way to handle this situation is to present them an elegant table sporting an alternate color scheme for TRs.

11. Fix Broken Img Links
$('img').error(function(){
$(this).attr('src', ‘img/broken.png’);
});

It is very time-consuming as well as infuriating to check each and every image broken link and fix it manually. To save yourself from this trouble, you can use the above script to fix all the broken links at once.

12. Verify Checkbox is Checked

Single Checkbox:

$('#checkBox').attr('checked');

All Checkbox:

$('input[type=checkbox]:checked');

Whether you want to check if a single checkbox or multiple checkboxes are checked, you can do this using the abovementioned code. However, the code is only compatible with jQuery v 1.5 for v 1.6 replace ‘.attr’ with ‘.prop’.

13. Swap Input Fields
<!-- jQuery -->
$('input[type=text]').focus(function(){   
           var $this = $(this);
           var title = $this.attr('title');
           if($this.val() == title)
           {
               $this.val('');
           }
}).blur(function() {
           var $this = $(this);
           var title = $this.attr('title');
           if($this.val() == '')
           {
               $this.val(title);
           }
});

Swap or simply input fields are used to educate the visitor what they should write in a particular field. With the abovementioned script, the field will display the required text – take for instance ‘your name’ – which will be immediately swapped once the click is focused on the field.

14. Email Address Validation
(function ($) {
	$.fn.validateEmail = function () {
		return this.each(function () {
			var $this = $(this);
			$this.change(function () {
				var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
				if ($this.val() == "") {
					$this.removeClass("badEmail").removeClass("goodEmail")
				}else if(reg.test($this.val()) == false) {
					$this.removeClass("goodEmail");
					$this.addClass("badEmail");
				}else{
					$this.removeClass("badEmail");
					$this.addClass("goodEmail");
				}
			});
		});
	};
})(jQuery);

A totally ‘must-have’ script, email validation library is necessary for every website having ‘contact-us’ form or an opt-in form to make sure that every user provides a valid email address. If the user enters a wrong email address, he will be immediately prompted with an ‘invalid-email’ message.

15. Open External Links in New Window
$('a').each(function() {  
  var a = new RegExp('/' + [removed].host + '/');  
  if(!a.test(this.href)) {  
    $(this).click(function(event) {  
      event.preventDefault();  
      event.stopPropagation();  
      window.open(this.href, '_blank');  
    });  
 }  
});

Manually attributing all the external links on your web page with ‘target=”_blank”’ can be a very frustrating task. You can avoid this hectic task by using the above given script.

Wrapping Up

The jQuery snippets I presented in the extensive aforementioned list are the most popular and commonly used scripts that majority of websites use. Feel free to use the scripts at your discretion and let me know if it worked or not- though I am sure it will definitely work. Enjoy!

Like it? Share it.

4 Comments

  1. Thanks, some good stuff here for sure…;)

    I doubt a real web developer would use number two since anyone that knows anything about building websites will know what a waste of time that is.

  2. For Verify Checkbox is Checked I prefer using:

    $(‘#checkbox’).is(‘:checked’);

    Makes it more readable

  3. Very cool ths snipplets, but for Mobile Detection I´d recomment this: http://detectmobilebrowsers.com/

    ; )

  4. 3. Use “prop” instead “attr”: $(‘input[type="submit"]‘).attr(“prop”, true/false);
    8. “live” is deprecated binding method, use “on” instead: $(document).on(“click”, “a.popup”, function() {…});
    9. use “setTimeout” instead “setInterval”. “setInterval” has performance issues;
    13. Binding should be inside “on”: $(‘input[type=text]‘).on(blur: function(){…}, focus: function(){…});
    On click events stoping need use: event.preventDefault();event.stopPropagation();

Leave a Comment Yourself

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>