search
HomeWeb Front-endJS Tutorial26 practical tips under Jquery (jQuery tips, tricks & solutions)_jquery

For example, there are functions such as disabling right-clicking, hiding search text box text, opening links in new windows, detecting browsers, preloading images, switching page styles, equal heights of all columns, dynamically controlling page font size, and obtaining the X value and Y value of the mouse pointer. , verify whether the element is empty, replace the element, lazy load, verify whether the element exists in the Jquery collection, make the DIV clickable, clone the object, center the element, count the number of elements, use the Jquery class library on the Google host, disable Jquery The effect is to solve the conflict problem between Jquery class library and other Javascript class libraries.

The details are as follows:

1. Right-click is prohibited

Copy code The code is as follows:

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

2. Hide the search text box text
Copy code The code is as follows :

$(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 in new Open the link in the window
Copy the code The code is as follows:

$(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 use
open link

4 Detect browser
Note: In version jQuery 1.4, $.support replaced the $.browser variable.
Copy code The code is as follows:

$(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 // do something
}
// Target anything above IE6
if ($.browser.msie && $.browser.version > 6){
// do something
}
});

5 Preload images
Copy code The code is as follows:

$(document).ready(function() {
jQuery.preloadImages = function()
{
for(var i = 0; i").attr("src", arguments [i]);
}
};
// how to use
$.preloadImages("image1.jpg");
});

6 Page style switching
Copy code The code is as follows:

$(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 links
Default Theme A>
Red Theme
Blue Theme< ;/A>
});

7 columns have the same height
If two CSS columns are used, this method can be used to make the heights of the two columns the same.
Copy code The code is as follows:

$(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
Copy the code The code is as follows:

$(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 of the page function
Copy code The code is as follows:

$(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 link
go to top
});

10 Get the mouse pointerXY value
Copy code The code is as follows:

$ (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 Verify whether the element is empty
Copy code The code is as follows:

$(document).ready(function() {
if ($('#id').html()) {
// do something
}
});

12 Replacement elements
Copy code The code is as follows:

$(document).ready(function() {
$('#id').replaceWith('
I have been replaced

');
});

13 jQuery delayed loading function
Copy code The code is as follows:

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

14 Remove word function
Copy code The code is as follows:

$(document).ready(function() {
var el = $('#id');
el.html(el.html().replace(/word /ig, ""));
});

15 Verify whether the element exists in the Jquery object collection
Copy code The code is as follows:

$(document).ready(function() {
if ($('#id').length) {
// do something
}
});

16 Make the entire DIV clickable
Copy the code The code is as follows:

$( 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 use

});

17 Switch between ID and Class When changing the Window size, switch between ID and Class
Copy code The code is as follows:

$(document).ready(function() {
function checkWindowSize() {
if ( $(window).width() > 1200 ) {
$('body').addClass('large');
}
else {
$('body').removeClass('large');
}
}
$(window).resize(checkWindowSize);
});

18 Clone object
Copy code The code is as follows:

$(document).ready(function () {
var cloned = $('#id').clone();
// how to use

});

19 Position the element in the middle of the screen
Copy the code The code is as follows:

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

20 Write your own selector
Copy code The code is as follows:

$(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');
});
});

21 statistical elements Number
Copy code The code is as follows:

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

22 Use your own Bullets
Copy the code The code is as follows:

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

23 Reference the Jquery class library on Google host Let Google host the jQuery script for you. This can be done in 2 ways.
Copy Code The code is as follows:

//Example 1

// Example 2:(the best and fastest way)


24. Disable Jquery (animation) effect
Copy code The code is as follows:

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

25. Solution to conflicts with other Javascript libraries
Copy code The code is as follows:

$(document).ready(function() {
var $ jq = jQuery.noConflict();
$jq('#id').show();
});

26. Application of Load() function (page load Enter the prompt):

> First write the CSS and position it absolutely to the upper right corner of the page.
Copy code The code is as follows:

#loading {
position:absolute; z- index:900;text-align:center;
background-color:#eef2fa;border:1px solid #d8e3e8;
color:#000;font-size:12px;padding:3px;width:80px;
right:0;top:0;
}

> Then use jQuery to hide the Loading DIV after all images are loaded.
> Don’t forget to load jQuery library. When I was testing the code just now, I wrote the wrong address and almost went crazy.
Copy code The code is as follows:

<script> <BR>jQuery(document). ready(function($){ <BR>$('img').load(function(){ <BR>                $('#loading').css("display","none"); <BR>}) ; <BR>}); <BR></script>

> Just insert a DIV anywhere, O(∩_∩)O haha.
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 Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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 Article

Hot Tools

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool