Home > Article > Web Front-end > 35 jQuery code snippets that programmers must know
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; }); });
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); } }); }
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
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 } });
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"); });
6. Page style switching
$(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// the linksDefault ThemeRed ThemeBlue Theme});
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")); }); });
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 = $('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 function 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// the linkgo to top});
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});
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 $('a.top').click(function () { $(document.body).animate({scrollTop: 0}, 800); return false; }); Back to top
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++) { $('').attr('src', arguments[i]); } }; $.preloadImages('img/hover1.png', 'img/hover2.png');
13. Check whether the image is loaded
Sometimes you need to ensure that the image is loaded in order to perform the following operations:
$('img').load(function () { console.log('image load successful'); });
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:
$('img').on('error', function () { $(this).prop('src', 'img/broken.png'); });
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:
$('.btn').hover(function () { $(this).addClass('hover'); }, function () { $(this).removeClass('hover'); }); 你只需要添加必要的CSS代码即可。如果你想要更简洁的代码,可以使用 toggleClass 方法: $('.btn').hover(function () { $(this).toggleClass('hover'); });
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:
$('input[type="submit"]').prop('disabled', true);
All you have to do is execute the removeAttr method and pass in the attribute to be removed as a parameter:
$('input[type="submit"]').removeAttr('disabled');
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:
$('a.no-link').click(function (e) { e.preventDefault(); });
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 $('.btn').click(function () { $('.element').fadeToggle('slow'); }); // Toggle $('.btn').click(function () { $('.element').slideToggle('slow'); });
19. Simple Accordion Effect
Here is 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 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 = $('.column'); var height = 0; $columns.each(function () { if ($(this).height() > height) { height = $(this).height(); } }); $columns.height(height);
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 ($('#id').html()) { // do something } });
22. Replace the element
$(document).ready(function() { $('#id').replaceWith('I have been replaced'); });
23. jQuery delayed loading function
$(document).ready(function() { window.setTimeout(function() { // do something }, 1000); });
24. Word removal function
$(document).ready(function() { var el = $('#id'); el.html(el.html().replace(/word/ig, "")); });
25. Verify whether 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 usehome});
27. ID与Class之间转换
当改变Window大小时,在ID与Class之间切换
$(document).ready(function() { function checkWindowSize() { if ( $(window).width() > 1200 ) { $('body').addClass('large'); } else { $('body').removeClass('large'); } } $(window).resize(checkWindowSize); });
28. 克隆对象
$(document).ready(function() { var cloned = $('#id').clone(); // how to use});
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(); });
30. 写自己的选择器
$(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. 统计元素个数
$(document).ready(function() { $("p").size(); });
32. 使用自己的 Bullets
$(document).ready(function() { $("ul").addClass("Replaced"); $("ul > li").prepend("‒ "); // how to use ul.Replaced { list-style : none; } });
33. 引用Google主机上的Jquery类库
//Example 1
34. 禁用Jquery(动画)效果
$(document).ready(function() { jQuery.fx.off = true; });
35. 与其他Javascript类库冲突解决方案
$(document).ready(function() { var $jq = jQuery.noConflict(); $jq('#id').show(); });
以上就是本章的全部内容,更多相关教程请访问jQuery视频教程!