5 Useful jQuery Code Snippets For Developers

This post provides a list of 5 useful jQuery code snippets that every web developer must have in his kitty. These are useful for implementing different day-to-day tasks. These snippets can be used to change the button text on click, disable text selection on the website, check Internet connectivity, randomly change the element’s color and/or create an overlay div element. Check it out!

1. Change button text once clicked

The jQuery code below changes the button text once it is clicked. You may need this to inform users that the button has been clicked. As an example, when a ‘submit’ button is clicked, you could change the button text to read “submitting,” and when the request has been processed the text could change again it say “submitted”.

$(document).ready(function(){
    $("#btnSubmit").click(function(){
    	$(this).val("Submitting...");
		//Actual code goes here…
	 	$(this).val("Submitted...");
    });
});

2. Disable text selection on the website

If you wish to restrict text selection or disable copying text from your website, the following jQuery code would help you to achieve this goal. The following jQuery code will disable text selection from all SPAN, Paragraph and DIV elements present on the page. If you integrate this piece of code globally, then you can restrict the text selection for SPAN, Paragraph and DIV elements for the complete website.

$(document).ready(function(){
$('span,p,div').attr('unselectable', 'on')
         .css('user-select', 'none')
         .on('selectstart', false);
});

3. Check Internet Connectivity using jQuery

Sometimes before executing a piece of code, you need to check the Internet connectivity. The following jQuery code uses the navigator.onLine() property to see if the browser is online or offline.

$(document).ready(function() {
  function checkInternet() {
    var status = navigator.onLine;
    if (status)
      return true;
    else
      return false;
  }
   var bIsInternetAvailable = checkInternet(); 
});

Alternatively, you can also check with the jQuery library itself. The following jQuery code references the jQuery library from Google CDN. Google CDN is up 99.99% of the time. If the jQuery library is not loaded, the window.jQuery returns false.

4. Random background color change for any element

The following jQuery code will change the background color of DIV elements every 2 seconds. This code first creates a random color number using the Math.random() function and then using jQuery .css() method, assigns the background-color CSS property to the random color value.

$(document).ready(function() {
  function ApplyColor() {
    var randomColor = Math.floor(Math.random() * 16777215).toString(16);
    $('div').css("background-color", '#' + randomColor);
    setTimeout(changeColor, 2000);
  }
  ApplyColor();
});

The problem with the above code is that we don’t have any control over the selection of the color. The randomly generated color may not suit the element design so it’s better to first define a set of colors and let the code choose the color from the defined set. The following jQuery code defines an array of 4 colors and then the code picks up any one item randomly from the array and applies the same.

function ApplyColor() {
  var rndColors = ["#00FF00", "#CCCCCC", "#995499", "#FF9900"];
  var selColor = Math.floor(Math.random() * rndColors.length);
  $('div').css("background-color", rndColors[selColor]);
  setTimeout(changeColor, 2000);
}

5. Create overlay div on screen and remove it on click

An overlay is a DIV element that stays fixed on the screen (even when you scroll) and has some opacity to create a layer effect. The following jQuery code creates an overlay DIV and appends it to HTML body. It is then removed when clicked.

$(document).ready(function() {
  $('

‘) .css({ position: ‘fixed’, top: 0, left: 0, right: 0, bottom: 0, opacity: 0.8, background: ‘DarkGrey’, display: ‘none’ }) .appendTo(‘body’) .fadeIn(‘normal’) .click(function() { $(this).fadeOut(‘slow’, function() { $(this).remove(); }) }); });

Conclusion

To sum it up, these handy jQuery code snippets provide solutions for several different functionalities and should absolutely be in your toolbox. These tiny snippets can save you time, and allow you to implement with ease on the client side. Feel free to use these snippets at will!


Leave a Comment

IMPORTANT:

  • If you wish to post code examples, please wrap them in <code> tags.
  • Multi-line code should be wrapped in <pre><code> </code></pre>
  • Use &lt; instead of < and &gt; instead of > in the examples themselves. Otherwise, you could lose part of the comment when it's submitted.