search
HomeWeb Front-endJS TutorialPay attention to jquery skills and improve jquery skills (must learn for front-end development)_jquery

A collection of simple tips to help you improve your jQuery skills.

A small project started by Matt Smith, there are currently 14 tips. Bole Online will continue to follow up with updates.

Back to top button
Preload images
Check if the image is loaded
Automatically repair damaged pictures
Class switch on Hover
Disable input fields
Stop link loading
Fade/slide switch
Simple folding effect
Set two Divs to the same height
Open external link in new window
Find the text element
Switch between visible and hidden triggers

Back to top button

By using the animate and scrollTop methods in jQuery, you can create a simple back to top animation without the need for a plugin:

JavaScript

// Back to top
$('a.top').click(function (e) {
 e.preventDefault();
 $(document.body).animate({scrollTop: 0}, 800);
});

JavaScript

<!-- Create an anchor tag -->
<a class="top" href="#">Back to top</a>

Change the value of scrollTop to where you want the scrollbar to stop. And then what you do is, set it to go back to the top in 800 milliseconds.

Preload images

If your page uses a lot of images that are not initially visible (e.g. bound to hover), it is useful to preload them:

JavaScript

$.preloadImages = function () {
 for (var i = 0; i < arguments.length; i++) {
  $('<img  alt="Pay attention to jquery skills and improve jquery skills (must learn for front-end development)_jquery" >').attr('src', arguments[i]);
 }
};
$.preloadImages('img/hover-on.png', 'img/hover-off.png');

Check whether the image is loaded

Sometimes you may need to check whether the image is completely loaded before you can perform subsequent operations in the script:

JavaScript

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

You can also check whether a specific image has been loaded by replacing the img tag with an ID or class.

Automatically repair damaged pictures

If you find that the image links on your website are broken, it will be troublesome to replace them one by one. This simple code can help a lot:

JavaScript

$('img').on('error', function () {
 $(this).prop('src', 'img/broken.png');
});

Even if you don’t have any broken links, adding this code will have no impact.

Class switching on Hover

If the user's mouse hovers over a clickable element on the page, you want to change the visual representation of this element. You can use the following code to add a class to the element when the user hovers it; remove the class when the user leaves the mouse:

JavaScript

$('.btn').hover(function () {
 $(this).addClass('hover');
}, function () {
 $(this).removeClass('hover');
});

You only need to add the necessary CSS. If you need a simpler way, you can also use the toggleClass method:

JavaScript

$('.btn').hover(function () {
 $(this).toggleClass('hover');
});


Note: CSS may be a faster solution for this example, but it’s still worth knowing.

Disable input field

Sometimes you may want to make a form's submit button or its text input box unavailable until the user performs a specific action (such as confirming the "I have read the terms" checkbox). Add disabled attribute to your input to achieve the effect you want:

JavaScript

$('input[type="submit"]').prop('disabled', true);

When you want to change the value of disabled to false, just run the prop method on the input again.

JavaScript

$('input[type="submit"]').prop('disabled', false);

Stop link loading

Sometimes you don’t want a link to jump to a page or reload the page, but want to be able to do something else, such as trigger other scripts. The following code is a little trick to disable the default behavior:

JavaScript

$('a.no-link').click(function (e) {
 e.preventDefault();
});

Fade/slide switch

Fade in and out and slide are animation effects that we often use jQuery to create. Maybe you just want to reveal an element when the user clicks on something, using fadeIn and slideDown are both great. But if you want the element to appear on the first click and disappear on the second click, the following code can do the job well:

JavaScript

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

Simple accordion effect

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

JavaScript

// 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;
});

After adding this script, all you need to do is see if the script works properly within the necessary HTML.

Make the two Divs the same height

Sometimes you might want two divs to have the same height, regardless of what content they contain:

JavaScript

$('.div').css('min-height', $('.main-div').height());

This example sets min-height, meaning it can be larger than the main div, but never smaller. But a more flexible method is to iterate through the settings of a set of elements and set the height to the highest value in the element:

JavaScript

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

If you want all columns to be the same height:

JavaScript

var $rows = $('.same-height-columns');
$rows.each(function () {
 $(this).find('.column').height($(this).height());
});

在新标签/窗口打开站外链接
在一个新标签或者新窗口中打开外置链接,并确保站内链接会在相同的标签或窗口中打开:

JavaScript

$('a[href^="http"]').attr('target', '_blank');
$('a[href^="//"]').attr('target', '_blank');
$('a[href^="' + window.location.origin + '"]').attr('target', '_self');

注意:window.location.origin 在 IE 10 中不可用,该 issue 的修复方法。

通过文本找到元素

通过使用 jQuery 中的 contains() 选择器,你可以找到某个元素中的文本。如果文本不存在,该元素将会隐藏:

JavaScript

var search = $('#search').val();

$('div:not(:contains("' + search + '"))').hide();

视觉改变触发
当用户焦点在另外一个标签上,或重新回到标签时,触发 JavaScript:

JavaScript

$(document).on('visibilitychange', function (e) {
 if (e.target.visibilityState === "visible") {
  console.log('Tab is now in view!');
 } else if (e.target.visibilityState === "hidden") {
  console.log('Tab is now hidden!');
 }
});

Ajax 调用的错误处理

当某次 Ajax 调用返回 404 或 500 错误,就会执行错误处理。但如果没有定义该处理,其他 jQuery 代码或许会停止工作。可以通过下面这段代码定义一个全局 Ajax 错误处理:

JavaScript

$(document).ajaxError(function (e, xhr, settings, error) {
 console.log(error);
});

全能程序员交流QQ群290551701,群内程序员都是来自,百度、阿里、京东、小米、去哪儿、饿了吗、蓝港等高级程序员 ,拥有丰富的经验。加入我们,直线沟通技术大牛,最佳的学习环境,了解业内的一手的资讯。如果你想结实大牛,那 就加入进来,让大牛带你超神!

Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor