14 Useful jQuery Snippets

snippets

Years back jQuery has become one of the must-have items for every developer jQuery is one of the most used libraries, making DOM manipulation easy and fast. The reason why jQuery is so popular is its simplicity. We can almost do whatever we want with this powerful library. In addition to all the open possibilities provided by jQuery, some snippets are often returned. Introducing 14 snipets that are useful for everyone from beginner to advanced developer.

1) BUTTONS TO BACK TO TOP

// Back to top
$ ('a.top'). click (function () {
   $ (document.body) .animate ({scrollTop: 0}, 800);
   return false;
});
// HTML link to the top
<a class="top" href=[#"> Back to Top </a>

As you can see, using the animate and scrollTop features in jQuery, we don’t need a simple animation plugin to get back to the top of the page.
By changing the value of the scrollTop function we can determine where we want the page to stop, in this case we used the value 0 so we want it to go all the way to the top of the page, for example if you want to return to 100px from the top of the page, simply type instead of zero 100px in the function.
So what really happens with the application of this code is an animation of the document to go back to the top of the page in 800ms.

2) MAKING SURE THE PICTURES ARE LOADED

$(‘img’).load(function() {
  console.log(‘image load successful’);
});

Sometimes you want to make sure the images on the page are fully readable so you can continue with further scripts, with these three lines of jQurey you can easily check it.
You can also check one image individually by replacing the img tag with an ID or class.

3) ADDING THE CLASS TO HOVER

$(‘.btn').hover(function() {
  $(this).addClass(‘hover’);
}, function() {
  $(this).removeClass(‘hover’);
}
);

We usually want the appearance of elements that have a function to be variable when the user moves the cursor over them. This jQuery snipet does just that, adds a class element while the mouse pointer is on it, as soon as the user moves the mouse from that element the class disappears, so all it takes is to add styles to your CSS file.

4) EXCLUDING DATA ENTRY FIELDS

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

If you want the check box or input fields to be turned off until the user performs a specific action beforehand (e.g., “I have read the Terms of Use” check) this line of code enables this. Adds the disabled attribute to fields so you can include them when you want.
To do this, you need to run the removeAttr function in a field that has a disabled parameter.

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

5) TOGGLE FADE/SLIDE

// Fade
$( “.btn" ).click(function() {
  $( “.element" ).fadeToggle("slow");
});
// Toggle
$( “.btn" ).click(function() {
  $( “.element" ).slideToggle("slow");
});

Slide and Fade is something that is often used for animations in jQuery, if we want an element to appear when we click on something, fadeIn and slideDown are ideal methods, but if we want that element to appear at the first click and disappear at the second click , this code will do the job.

6) EASY ACCORDION

// Close all panels
&nbsp;
$('#accordion').find(‘.content').hide();
// Accordion
$('#accordion').find(‘.accordion-header').click(function(){
  var next = $(this).next();
  next.slideToggle('fast’);
  $(‘.content’).not(next).slideUp('fast’);
  return false;
});

By adding this script all you have to do is add the necessary HTML code that will make this accordion work.
As you can see in this code, first all the panels are closed and then clicking the content associated with the header is displayed and the others are closed.

7) EQUALIZING THE HEIGHT OF THE TWO DIV

$(‘.div').css('min-height', $(‘.main-div').height());

If you want two divs to be the same height no matter what the content is, this code line does just that. In this case, the min-height is set, which means that it can be larger than the main div, but by no means smaller. This is great for masonry sites.

8) „ZEBRA“ LIST

$('li:odd').css('background', '#E8E8E8’);

With this line of code you can easily create zebra lists, this sets a defined background color for each odd element of the list. This code is applicable to every element from table to div.

9) LOADING THE EXTERNAL CONTENT

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

Want to add content from another page to the div? This is pretty easy with jQuery.

10) PLACING THE DIV ON THE WHOLE WIDTH / HEIGHT

// global variables
var winWidth = $(window).width();
var winHeight = $(window).height();
// setting the initial height and width of the div
$('div').css({
  'width': winWidth,
  'height': winHeight,
});
// the width and height of the div when resizing windows
$(window).resize(function() {
  $('div').css({
    'width': winWidth,
    'height': winHeight,
  });
});

This code is ideal for modal windows or popups.

11) AUTOMATIC CONTROL LOADING WITH SCROLL

var loading = false;
$(window).scroll(function() {
  if((($(window).scrollTop()+$(window).height())+250)&gt;=$(document).height()) {
    if(loading == false) {
      loading = true;
      $('#loadingbar').css("display","block");
      $.get("load.php?start="+$('#loaded_max').val(), function(loaded) {
        $('body').append(loaded);
        $('#loaded_max').val(parseInt($('#loaded_max').val())+50);
        $('#loadingbar').css("display","none");
        loading = false;
      });
    }
  }
});
$(document).ready(function() {
  $('#loaded_max').val(50);
});

Some websites like Twitter or Facebook load content while scrolling. Which means that all content is dynamically loaded as long as you scroll.

12) ALPHABETICAL SORTING OF THE LIST

$(function() {
  $.fn.sortList = function() {
    var mylist = $(this);
    var listitems = $('li', mylist).get();
    listitems.sort(function(a, b) {
      var compA = $(a).text().toUpperCase();
      var compB = $(b).text().toUpperCase();
      return (compA &lt; compB) ? -1 : 1;
    });
    $.each(listitems, function(i, itm) {
      mylist.append(itm);
    });
  }
  $("ul#demoOne").sortList();
});

In some cases, it can be very helpful to sort through a long list. This code allows the list to be sorted in alphabetical order.

13) ADD HTML

var sometext = "here is more HTML";
$("p#text1").append(sometext); // added after
$("p#text1").prepend(sometext); // added before

Using the .append () method, we can easily add HTML code directly to the DOM. You can add new HTML defined in a variable or clone existing HTML from a page.

14) EXTERNAL LINKS OPENING IN NEW TABS

$('a').each(function() {
  var a = new RegExp('/' + window.location.host + '/');
  if(!a.test(this.href)) {
    $(this).click(function(event) {
      event.preventDefault();
      event.stopPropagation();
      window.open(this.href, '_blank');
    });
  }
});

The target = ”_ blank” attribute allows links to be opened in new tabs. It is recommended that external links open in new tabs, while internal links should open in the same window.
This code detects if the link is external, if so adds the target = ”_ blank” attribute.

Likes:
15 0
Views:
2194
Article Categories:
PROGRAMMINGTECHNOLOGY

Leave a Reply

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