Home > Web Front-end > JS Tutorial > 35 jQuery code snippets that programmers must know

35 jQuery code snippets that programmers must know

PHPz
Release: 2018-09-29 09:16:33
Original
1244 people have browsed it

jQuery has now become the most popular JavaScript library in web development. Through jQuery and a large number of plug-ins, you can easily achieve various gorgeous effects. This article will introduce you to some practical jQuery skills, hoping to help you use jQuery more efficiently.

Collected 35 jQuery tips/code snippets to help you develop quickly.

1. Disable right-click

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

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); }
   });
}
Copy after login

3. 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 useopen link
Copy after login

4. Detect browser

Note: In version jQuery 1.4, $.support replaced 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
}
});
Copy after login

5. Preload 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(?").attr("src", arguments[i]);
 }
}
// how to use
$.preloadImages("image1.jpg");
});
Copy after login

6. Page style switching

$(document).ready(function() {
  $("a.Styleswitcher").click(function() {
    //swicth the LINK REL attribute with the value in A REL attribute
    $(&#39;link[rel=stylesheet]&#39;).attr(&#39;href&#39; , $(this).attr(&#39;rel&#39;));
  });
// how to use
// place this in your header// the linksDefault ThemeRed ThemeBlue Theme});
Copy after login

7. The column heights are the same

If two CSS columns are used, this method can be used to make the heights of the two columns the same .

$(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"));
});
});
Copy after login

8. Dynamically control the page font size

Users can change the page font size

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

9. Return to the top function of the page

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

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
  $(&#39;#XY&#39;).html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
 });
// how to use});
Copy after login

11. Back to top button

You can use animate and scrollTop to implement the animation of returning to the top without using other plug-ins.

// Back to top
$(&#39;a.top&#39;).click(function () {
 $(document.body).animate({scrollTop: 0}, 800);
 return false;
});
Back to top
Copy after login

Changing the value of scrollTop can adjust the distance between the return and the top, and the second parameter of animate is the time required to perform the return action (unit: milliseconds).

12. Preload images

If your page uses a lot of invisible images (such as hover display), you may need to preload them:

$.preloadImages = function () {
 for (var i = 0; i < arguments.length; i++) {
  $(&#39;&#39;).attr(&#39;src&#39;, arguments[i]);
 }
};
$.preloadImages(&#39;img/hover1.png&#39;, &#39;img/hover2.png&#39;);
Copy after login

13. Check whether the image is loaded

Sometimes you need to ensure that the image is loaded in order to perform the following operations:

$(&#39;img&#39;).load(function () {
 console.log(&#39;image load successful&#39;);
});
Copy after login

You can replace img with other ID or class to check whether the specified image is loaded.

14. Automatically modify broken images

If you happen to find a broken image link on your website, you can replace it with an image that cannot be easily replaced they. Adding this simple code can save you a lot of trouble:

$(&#39;img&#39;).on(&#39;error&#39;, function () {
 $(this).prop(&#39;src&#39;, &#39;img/broken.png&#39;);
});
Copy after login

Even if your site doesn’t have broken image links, there’s no harm in adding this code.

15. Mouse hover (hover) switching class attribute

If when the user hovers the mouse over a clickable element, you want to change its effect, The following code can add a class attribute when it is hovering over an element, and automatically cancel the class attribute when the user mouses away:

$(&#39;.btn&#39;).hover(function () {
 $(this).addClass(&#39;hover&#39;);
 }, function () {
  $(this).removeClass(&#39;hover&#39;);
 });
你只需要添加必要的CSS代码即可。如果你想要更简洁的代码,可以使用 toggleClass 方法:
$(&#39;.btn&#39;).hover(function () { 
 $(this).toggleClass(&#39;hover&#39;); 
});
Copy after login

Note: Using CSS directly to achieve this effect may be a better solution, but you still need to know the method.

16. Disable input fields

Sometimes you may need to disable a form's submit button or an input field until the user performs some action (for example, check " Read the terms" checkbox). You can add the disabled attribute until you want to enable it:

$(&#39;input[type="submit"]&#39;).prop(&#39;disabled&#39;, true);
Copy after login

All you have to do is execute the removeAttr method and pass in the attribute to be removed as a parameter:

$(&#39;input[type="submit"]&#39;).removeAttr(&#39;disabled&#39;);
Copy after login

17. Prevent links from loading

Sometimes you don’t want to link to a page or reload it, you may want it to do something else or trigger something For other scripts, you can do this:

$(&#39;a.no-link&#39;).click(function (e) {
 e.preventDefault();
});
Copy after login

18. Switch fade/slide

fade and slide are what we use Animation effects are often used in jQuery to make elements appear better. But if you want the first effect to be used when the element is displayed and the second effect to be used when it disappears, you can do this:

// Fade
$(&#39;.btn&#39;).click(function () {
 $(&#39;.element&#39;).fadeToggle(&#39;slow&#39;);
});
// Toggle
$(&#39;.btn&#39;).click(function () {
 $(&#39;.element&#39;).slideToggle(&#39;slow&#39;);
});
Copy after login

19. Simple Accordion Effect

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

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

20. Make two DIVs have the same height

Sometimes you need to make two divs the same height, regardless of the content inside them. You can use the following code snippet:

var $columns = $(&#39;.column&#39;);
var height = 0;
$columns.each(function () {
 if ($(this).height() > height) {
  height = $(this).height();
 }
});
$columns.height(height);
Copy after login

This code will loop through a group of elements and set their height to the maximum height among the elements.

21. Verify whether the element is empty

This will allow you to check if an element is empty.
$(document).ready(function() {
 if ($(&#39;#id&#39;).html()) {
  // do something
  }
});
Copy after login

22. Replace the element

$(document).ready(function() {
  $(&#39;#id&#39;).replaceWith(&#39;I have been replaced&#39;);
});
Copy after login

23. jQuery delayed loading function

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

24. Word removal function

$(document).ready(function() {
  var el = $(&#39;#id&#39;);
  el.html(el.html().replace(/word/ig, ""));
});
Copy after login

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

$(document).ready(function() {
  if ($(&#39;#id&#39;).length) {
 // do something
 }
});
Copy after login

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 usehome});
Copy after login

27. ID与Class之间转换

当改变Window大小时,在ID与Class之间切换

$(document).ready(function() {
  function checkWindowSize() {
  if ( $(window).width() > 1200 ) {
    $(&#39;body&#39;).addClass(&#39;large&#39;);
  }
  else {
    $(&#39;body&#39;).removeClass(&#39;large&#39;);
  }
  }
$(window).resize(checkWindowSize);
});
Copy after login

28. 克隆对象

$(document).ready(function() {
  var cloned = $(&#39;#id&#39;).clone();
// how to use});
Copy after login

29. 使元素居屏幕中间位置

$(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();
});
Copy after login

30. 写自己的选择器

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

31. 统计元素个数

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

32. 使用自己的 Bullets

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

33. 引用Google主机上的Jquery类库

//Example 1
Copy after login

34. 禁用Jquery(动画)效果

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

35. 与其他Javascript类库冲突解决方案

$(document).ready(function() {
  var $jq = jQuery.noConflict();
  $jq(&#39;#id&#39;).show();
});
Copy after login

以上就是本章的全部内容,更多相关教程请访问jQuery视频教程

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template