The programmer must know 35 jQuery snippets

  • 2020-10-07 18:34:05
  • OfStack

jQuery is now the most popular JavaScript library in Web development, and with jQuery and a lot of plug-ins, you can easily achieve all kinds of gorgeous effects. This article introduces you to 1 practical tips for jquery that will hopefully help you use jQuery more effectively.

A collection of 35 jQuery tips/code snippets to help you develop quickly.

1. Right click is prohibited


$(document).ready(function(){
  $(document).bind("contextmenu",function(e){
    return false;
  });
});

2. Hide the search text box text


Hide when clicked in the search field, the value.(example can be found below in the comment fields)
$(document).ready(function() {
$("input.text1").val("Enter your search text here");
  textFill($('input.text1'));
});
  function textFill(input){ //input focus text function
   var originalvalue = input.val();
   input.focus( function(){
     if( $.trim(input.val()) == originalvalue ){ input.val(''); }
   });
   input.blur( function(){
     if( $.trim(input.val()) == '' ){ input.val(originalvalue); }
   });
}

Open the link in a new window


XHTML 1.0 Strict doesn't allow this attribute in the code, so use this to keep the code valid.
$(document).ready(function() {
  //Example 1: Every link will open in a new window
  $('a[href^="http://"]').attr("target", "_blank");
  //Example 2: Links with the rel="external" attribute will only open in a new window
  $('a[@rel$='external']').click(function(){
   this.target = "_blank";
  });
});
// how to use
<a href="http://www.opensourcehunter.com" rel=external>open link</a>

4. Check your browser

Note: In version jQuery 1.4, the $.support variable is replaced with the $.browser variable


$(document).ready(function() {
// Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ){
  // do something
}
// Target Safari
if( $.browser.safari ){
  // do something
}
// Target Chrome
if( $.browser.chrome){
  // do something
}
// Target Camino
if( $.browser.camino){
  // do something
}
// Target Opera
if( $.browser.opera){
  // do something
}
// Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ){
  // do something
}
// Target anything above IE6
if ($.browser.msie && $.browser.version > 6){
  // do something
}
});

5. Pre-load images


This piece of code will prevent the loading of all images, which can be useful if you have a site with lots of images.
$(document).ready(function() {
jQuery.preloadImages = function()
{
 for(var i = 0; i<ARGUMENTS.LENGTH; jQuery(?<img { i++)>").attr("src", arguments[i]);
 }
}
// how to use
$.preloadImages("image1.jpg");
});

6. Page style switch


$(document).ready(function() {
  $("a.Styleswitcher").click(function() {
    //swicth the LINK REL attribute with the value in A REL attribute
    $('link[rel=stylesheet]').attr('href' , $(this).attr('rel'));
  });
// how to use
// place this in your header
<LINK rel=stylesheet type=text/css href="default.css">
// the links
<A href="#" rel=default.css>Default Theme</A>
<A href="#" rel=red.css>Red Theme</A>
<A href="#" rel=blue.css>Blue Theme</A>
});

7. The columns are of the same height

If two CSS columns are used, the height of the two columns can be the same in this manner.


$(document).ready(function() {
function equalHeight(group) {
  tallest = 0;
  group.each(function() {
    thisHeight = $(this).height();
    if(thisHeight > tallest) {
      tallest = thisHeight;
    }
  });
  group.height(tallest);
}
// how to use
$(document).ready(function() {
  equalHeight($(".left"));
  equalHeight($(".right"));
});
});

8. Dynamically control page font size

Users can change the font size of the page


$(document).ready(function() {
 // Reset the font size(back to default)
 var originalFontSize = $('html').css('font-size');
  $(".resetFont").click(function(){
  $('html').css('font-size', originalFontSize);
 });
 // Increase the font size(bigger font0
 $(".increaseFont").click(function(){
  var currentFontSize = $('html').css('font-size');
  var currentFontSizeNum = parseFloat(currentFontSize, 10);
  var newFontSize = currentFontSizeNum*1.2;
  $('html').css('font-size', newFontSize);
  return false;
 });
 // Decrease the font size(smaller font)
 $(".decreaseFont").click(function(){
  var currentFontSize = $('html').css('font-size');
  var currentFontSizeNum = parseFloat(currentFontSize, 10);
  var newFontSize = currentFontSizeNum*0.8;
  $('html').css('font-size', newFontSize);
  return false;
 });
});

9. Return to the top of the page


For a smooth(animated) ride back to the top(or any location).
$(document).ready(function() {
$('a[href*=#]').click(function() {
 if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
 && location.hostname == this.hostname) {
  var $target = $(this.hash);
  $target = $target.length && $target
  || $('[name=' + this.hash.slice(1) +']');
  if ($target.length) {
 var targetOffset = $target.offset().top;
 $('html,body')
 .animate({scrollTop: targetOffset}, 900);
  return false;
  }
 }
 });
// how to use
// place this where you want to scroll to
<A name=top></A>
// the link
<A href="#top">go to top</A>
});

10. Get the mouse pointer XY value


Want to know where your mouse cursor is?
$(document).ready(function() {
  $().mousemove(function(e){
   //display the x and y axis values inside the div with the id XY
  $('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
 });
// how to use
<DIV id=XY></DIV>
});

11. Return to the top button

You can use animate and scrollTop to return animations at the top without using other plug-ins.


Hide when clicked in the search field, the value.(example can be found below in the comment fields)
$(document).ready(function() {
$("input.text1").val("Enter your search text here");
  textFill($('input.text1'));
});
  function textFill(input){ //input focus text function
   var originalvalue = input.val();
   input.focus( function(){
     if( $.trim(input.val()) == originalvalue ){ input.val(''); }
   });
   input.blur( function(){
     if( $.trim(input.val()) == '' ){ input.val(originalvalue); }
   });
}
0

Changing the value of scrollTop adjusts the return distance from the top, while the second argument to animate is the time (in milliseconds) required to perform the return action.

12. Pre-load images

If you have a lot of invisible images on your page (hover), you may want to pre-load them:


$.preloadImages = function () {
 for (var i = 0; i < arguments.length; i++) {
  $('<img>').attr('src', arguments[i]);
 }
};
$.preloadImages('img/hover1.png', 'img/hover2.png');

13. Check that the image is loaded

Sometimes you need to make sure that the image is loaded in order to perform the following actions:


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

You can replace img with another ID or class to check that the specified image has been loaded.

14. Automatically modify damaged images

If you happen to find broken image links on your site, you can replace them with an image that is not easily replaced. Adding this simple code can save a lot of trouble:


Hide when clicked in the search field, the value.(example can be found below in the comment fields)
$(document).ready(function() {
$("input.text1").val("Enter your search text here");
  textFill($('input.text1'));
});
  function textFill(input){ //input focus text function
   var originalvalue = input.val();
   input.focus( function(){
     if( $.trim(input.val()) == originalvalue ){ input.val(''); }
   });
   input.blur( function(){
     if( $.trim(input.val()) == '' ){ input.val(originalvalue); }
   });
}
3

Even if your site doesn't have a broken image link, there's no harm in adding this code.

15. Mouse over (hover) toggle the class attribute

If you want to change the effect of a clickable element when the user hovers over it, the following code can add the class attribute when the user hovers over the element, and automatically cancel the class attribute when the user leaves:


Hide when clicked in the search field, the value.(example can be found below in the comment fields)
$(document).ready(function() {
$("input.text1").val("Enter your search text here");
  textFill($('input.text1'));
});
  function textFill(input){ //input focus text function
   var originalvalue = input.val();
   input.focus( function(){
     if( $.trim(input.val()) == originalvalue ){ input.val(''); }
   });
   input.blur( function(){
     if( $.trim(input.val()) == '' ){ input.val(originalvalue); }
   });
}
4

Note: Implementing this effect directly with CSS might be a better solution, but you still need to be aware of the method.

16. Disable the input field

Sometimes you might want to disable the submit button on the form or an input field until the user has done something (for example, check the "Read Terms" check box). You can add the disabled attribute until you want to enable it:

$('input[type="submit"]').prop('disabled', true);
All you have to do is execute the removeAttr method and pass in the property you want to remove as an argument:
$('input[type="submit"]').removeAttr('disabled');

17. Prevents the link from loading

Sometimes you don't want to link to a page or reload it, you might want it to do something else or trigger some other script, you can do this:


Hide when clicked in the search field, the value.(example can be found below in the comment fields)
$(document).ready(function() {
$("input.text1").val("Enter your search text here");
  textFill($('input.text1'));
});
  function textFill(input){ //input focus text function
   var originalvalue = input.val();
   input.focus( function(){
     if( $.trim(input.val()) == originalvalue ){ input.val(''); }
   });
   input.blur( function(){
     if( $.trim(input.val()) == '' ){ input.val(originalvalue); }
   });
}
5

18. Switching fade/slide

fade and slide are animations that we often use in jQuery to make elements look better. But if you want the element to display with the first effect and disappear with the second effect, you can do this:


Hide when clicked in the search field, the value.(example can be found below in the comment fields)
$(document).ready(function() {
$("input.text1").val("Enter your search text here");
  textFill($('input.text1'));
});
  function textFill(input){ //input focus text function
   var originalvalue = input.val();
   input.focus( function(){
     if( $.trim(input.val()) == originalvalue ){ input.val(''); }
   });
   input.blur( function(){
     if( $.trim(input.val()) == '' ){ input.val(originalvalue); }
   });
}
6

19. Simple accordion effect

Here's a quick and easy way to achieve an accordion effect:


// Close all panels
$('#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;
});

20. Make both DIV the same height

Sometimes you need to make both div the same height, no matter how much content they contain. You can use the following code snippet:


var $columns = $('.column');
var height = 0;
$columns.each(function () {
 if ($(this).height() > height) {
  height = $(this).height();
 }
});
$columns.height(height);

This code loops through a set of 1 elements and sets their height to the maximum height of the elements.

21. Verify the element is empty


Hide when clicked in the search field, the value.(example can be found below in the comment fields)
$(document).ready(function() {
$("input.text1").val("Enter your search text here");
  textFill($('input.text1'));
});
  function textFill(input){ //input focus text function
   var originalvalue = input.val();
   input.focus( function(){
     if( $.trim(input.val()) == originalvalue ){ input.val(''); }
   });
   input.blur( function(){
     if( $.trim(input.val()) == '' ){ input.val(originalvalue); }
   });
}
9

22. Replace elements


$(document).ready(function() {
  $('#id').replaceWith('
<DIV>I have been replaced</DIV>
');
});

23. jQuery delay loading function


$(document).ready(function() {
  window.setTimeout(function() {
   // do something
  }, 1000);
});

24. Remove word function


$(document).ready(function() {
  var el = $('#id');
  el.html(el.html().replace(/word/ig, ""));
});

25. Verify that the element exists in the jquery object collection


$(document).ready(function() {
  if ($('#id').length) {
 // do something
 }
});

26. Make the entire DIV clickable


$(document).ready(function() {
  $("div").click(function(){
   //get the url from href attribute and launch the url
   window.location=$(this).find("a").attr("href"); return false;
  });
// how to use
<DIV><A href="index.html">home</A></DIV>
});

27. Conversion between ID and Class

Switch between ID and Class when changing the size of Window


$(document).ready(function() {
  function checkWindowSize() {
  if ( $(window).width() > 1200 ) {
    $('body').addClass('large');
  }
  else {
    $('body').removeClass('large');
  }
  }
$(window).resize(checkWindowSize);
});

28. Clone objects


$(document).ready(function() {
  var cloned = $('#id').clone();
// how to use
<DIV id=id></DIV>
});

29. Place the element in the middle of the screen


$(document).ready(function() {
 jQuery.fn.center = function () {
   this.css("position","absolute");
   this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
   this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
   return this;
 }
 $("#id").center();
});

30. Write your own selector


$(document).ready(function() {
  $.extend($.expr[':'], {
    moreThen1000px: function(a) {
      return $(a).width() > 1000;
   }
  });
 $('.box:moreThen1000px').click(function() {
   // creating a simple js alert box
   alert('The element that you have clicked is over 1000 pixels wide');
 });
});

31. Count the number of elements


$(document).ready(function() {
  $("p").size();
});

Use your own Bullets


$(document).ready(function() {
  $("ul").addClass("Replaced");
  $("ul > li").prepend("‒ ");
 // how to use
 ul.Replaced { list-style : none; }
});

33. Reference the Jquery class library on the Google host


//Example 1
<SCRIPT src="http://www.google.com/jsapi"></SCRIPT>
<SCRIPT type=text/javascript>
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
  // do something
});
</SCRIPT><SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>
 // Example 2:(the best and fastest way)
<SCRIPT type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></SCRIPT>

34. Disable Jquery (animation) effects


$(document).ready(function() {
  jQuery.fx.off = true;
});

35. Conflict resolution with other Javascript libraries


$(document).ready(function() {
  var $jq = jQuery.noConflict();
  $jq('#id').show();
});

The above is the site to share programmers must know 35 jQuery code snippets, I hope you like.


Related articles: