Monday, August 15, 2016

Top 8 Jquery Trick You must know

1. Back to top
By using the method animate and scrolltop in jquery. You do not need to add any more plugin to create the scroll-to-top effect.
$('a.top').click(function (e) {
  e.preventDefault();
  $(document.body).animate({scrollTop: 0}, 800);
});
----
<a class="top" href="#">Back to top</a>

2.Preload images
If your site use multiple images and they have not been loaded then you can use an temporary image.
$.preloadImages = function () {
  for (var i = 0; i < arguments.length; i++) {
    $('<img>').attr('src', arguments[i]);
  }
};

$.preloadImages('img/hover-on.png', 'img/hover-off.png');

3.Check image loaded
$('img').load(function () {
  console.log('image load successful');
});

4.Toggle class on hover

If you want to change the class of an element when you mouse over. the following command can be applied
$('.btn').hover(function () {
  $(this).toggleClass('hover');
});

5.Disabling the Input field

Take an example when user click on the checkbox to agree a new term.
$('input[type="submit"]').prop('disabled', true);
$('input[type="submit"]').prop('disabled', false);

6.Prevent a default action
Ex. you click on a button link to redirect a special page but in some case you want to prevent this default action. Simply by using the following func.
$('a.no-link').click(function (e) {
  e.preventDefault();
});

7.Hide And show a div tag
you can apply Fade and Slide to toggle an element.

$('.btn').click(function () {
  $('.element').fadeToggle('slow');
});

// Toggle
$('.btn').click(function () {
  $('.element').slideToggle('slow');
});

8. Search element based on text
By using the method contains in jquery you can find the div tag that contain the div tag with keyword
var search = $('#search').val();
$('div:not(:contains("' + search + '"))').hide();

No comments:

Post a Comment