search
HomeWeb Front-endJS TutorialShare 12 practical jQuery code snippets_jquery

jQuery is an excellent JavaScript library that is very famous among WEB developers and web designers. It helps web designers develop many creative and beautiful WEB pages.

This article mainly shares 12 useful jQuery skills, the specific content is as follows

Here are some tips I’ve collected that will help you improve the creativity and functionality of your website layouts and applications.

1. Open the link in a new window

Using this code, when you click on a hypertext link, it will open in a new window, giving users a better experience:

$(document).ready(function() {
 //select all anchor tags that have http in the href
 //and apply the target=_blank
 $("a[href^='http']").attr('target','_blank');
});
 

2. Set timer

$(document).ready(function() {
 window.setTimeout(function() {
 // some code
 }, 500);
});

3. Set equal height columns

Use the following code to make each column in your web application have the same height:

<div class="equalHeight" style="border:1px solid">
 <p>First Line</p>
 <p>Second Line</p>
 <p>Third Line</p>
</div>
<div class="equalHeight" style="border:1px solid">
 <p>Column Two</p>
</div>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
 equalHeight('.equalHeight');
});
//global variable, this will store the highest height value
var maxHeight = 0;
function equalHeight(col) {
 //Get all the element with class = col
 col = $(col);
 //Loop all the col
 col.each(function() {
 //Store the highest value
 if ($(this).height() > maxHeight) {
 maxHeight = $(this).height();
 }
 });
 //Set the height
 col.height(maxHeight);
}
</script>

4. jQuery preloaded images

This trick can speed up the loading of images on web pages:

jQuery.preloadImagesInWebPage = function() {
 for (var ctr = 0; ctr & lt; arguments.length; ctr++) {
 jQuery("").attr("src", arguments[ctr]);
 }
}
// 使用方法:
$.preloadImages("image1.gif", "image2.gif", "image3.gif");
// 检查图片是否被加载
$('#imageObject').attr('src', 'image1.gif').load(function() {
 alert('The image has been loaded…');
});

5. Position the element in the middle of the page

<div id="foo" style="width:200px;height: 200px;background: #ccc;"></div>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
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;
}
//Use the above function as:
$('#foo').center();
</script>
 

6. Disable the right mouse button

$(document).ready(function() {
 //catch the right-click context menu
 $(document).bind("contextmenu", function(e) {
 //warning prompt - optional
 alert("No right-clicking!");
 //delete the default context menu
 return false;
 });
});

7. Calculate the number of sub-elements

<div id="foo">
 <div id="bar"></div>
 <div id="baz">
 <div id="biz"></div>
 <span><span></span></span>
 </div>
</div>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
 //jQuery code to count child elements $("#foo > div").size()
alert($("#foo > div").size())
</script>

8. Change style list

This code will help you change the style list.

 $(document).ready(function() {
 $("a.cssSwap").click(function() { 
 //swap the link rel attribute with the value in the rel 
 $('link[rel=stylesheet]').attr('href' , $(this).attr('rel')); 
 }); 
 });

9. Use jQuery to set text size

By adding this code, users can reset the text size (increase or decrease) according to their needs.

 $(document).ready(function() {
 //find the current font size
 var originalFontSize = $('html').css('font-size');

//Increase the text size
 $(".increaseFont").click(function() {
 var currentFontSize = $('html').css('font-size');
 var currentFontSizeNumber = parseFloat(currentFontSize, 10);

var newFontSize = currentFontSizeNumber*1.2;
 $('html').css('font-size', newFontSize);
 return false;
 });

//Decrease the Text Size
 $(".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;
 });

// Reset Font Size
 $(".resetFont").click(function(){
 $('html').css('font-size', originalFontSize);
 });
 });

10. Detect current mouse coordinates

Using this JS code, you can get mouse coordinates in any browser.

 $(document).ready(function() {
 $().mousemove(function(e)
 {
 $('# MouseCoordinates ').html("X Axis Position = " + e.pageX + " and Y Axis Position = " + e.pageY);
 });

11. Get the X/Y axis of the mouse pointer

 $().mousemove(function(e){
 //display the x and y axis values inside the P element
 $('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
 });

12. Return to top link

This code is very practical for relatively long pages. Users do not need to pull the scroll bar to return to the top, but can directly click "Return to Top".

 $(document).ready(function() {
 //when the id="top" link is clicked
 $('#top').click(function() {
 //scoll the page back to the top
 $(document).scrollTo(0,500);
 }
 });

jQuery is one of the best libraries for JavaScript, supporting Ajax and HTML script clients. It is mainly used for event processing and animation production. In addition, jQuery also has various plug-ins that allow developers to create web pages in the fastest time.

I hope this article will be helpful to everyone learning jquery programming.

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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

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

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

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

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

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

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

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

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

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

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

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

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

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

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

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.