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视频教程!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
