12 super useful JQuery code snippets

  • 2020-09-16 07:22:19
  • OfStack

This article has collected 12 very useful jQuery code snippets that you can copy and paste directly into the code, but developers should pay attention to understand the code before using it. Let's get up and enjoy the magic of the jQuery code.

1. Background switching effect of navigation menu

In the front page of the project, the activated navigation menu needs to have a different background than the other navigation menus. There are many ways to achieve this effect, and here is one using JQuery:


<ul id='nav'>
 <li> navigation 1</li>
 <li> navigation 2</li>
 <li> navigation 3</li>
</ul>
// Note: The code needs to be polished 
$('#nav').click(function(e) {
 //  Want to know siblings The use of 
$(e.target).addClass('tclass').siblings('.tclass').removeClass('tclass');;
 });

2. Reverse order access to elements in the JQuery object

In some scenarios, we might want to access the page element object fetched through the JQuery selector in reverse order. How does this work? Look at the code below:


 // To master JQuery The object's get methods   And the array of reverse Methods can be 
var arr = $('#nav').find('li').get().reverse();
$.each(arr,function(index,ele){
 .... ...
 });

3. Access elements in IFrame

In most cases, IFrame is not a good solution, but IFrame is used in projects for a variety of reasons, so you need to know how to access elements in IFrame


var iFrameDOM = $("iframe#someID").contents();
// And then, you can go through find Method to iterate over the fetch iFrame Elements in 
iFrameDOM.find(".message").slideUp();

4. Manage the value of the search box

Now every major website has a search box, and the search box usually has a default value, which disappears when the input box gets focus. Once the input field loses focus and no new value is entered in the input field, the value in the input field will revert to the default value. If a new value is entered in the input field, the value of the input field will be the value of the new input field. This effect is easy to achieve with JQuery:


$("#searchbox")
 .focus(function(){$(this).val('')})
 .blur(function(){
 var $this = $(this);
 // ' Please search ...' Is the default value for the search box 
 ($this.val() === '')? $this.val(' Please search ...') : null;
 });

5. Some pages load and update

In order to improve web performance, we usually do not load the entire page when there are updates, but only update part of the page content, such as lazy loading of images. The effects of partial page refreshes are also easy to implement in JQuery:


setInterval(function() { // every 5 Refresh the page content in seconds 
 // The content fetched will be added to  id for content After the elements of the 
 $("#content").load(url);
 }, 5000);

6. data method is adopted to cache data

In a project, to avoid repeated requests for data from the server, the acquired data is often cached for later use. JQuery can gracefully implement this function:


 var cache = {};
 $.data(cache,'key','value'); // Cache data 
 // To get the data 
 $.data(cache,'key');

7. Configure JQuery's compatibility with other libraries

If you are using JQuery in your project, $is the most common variable name, but JQuery is not the only 11 libraries that use $as variable names. To avoid naming conflicts, you can organize your code as follows:


// methods 1 :   for JQuery Rename as  $j
var $j = jQuery.noConflict();
$j('#id')....
 
// methods 2 :   Recommended ways to use it 
(function($){
 $(document).ready(function(){
 // Here, you can use it normally JQuery grammar 
 });
})(jQuery);

8. Clone table header to the bottom of the table

In order to make table more readable, we can clone a copy of the header information of the table to the bottom of the table. This special effect can be easily achieved through JQuery:


var $tfoot = $('<tfoot></tfoot>'); 
$($('thead').clone(true, true).children().get().reverse()).each(function(){
 $tfoot.append($(this));
});
$tfoot.insertAfter('table thead');

9. Create 1 full screen width and height (width/height) from Windows (viewport)

The following code allows you to create a full screen div based on viewport. This is very useful when displaying modal or dialogs in different window sizes:


$('#content').css({
 'width': $(window).width(),
 'height': $(window).height(),
});
// make sure div stays full width/height on resize
$(window).resize(function(){
 var $w = $(window);
 $('#content').css({
 'width': $w.width(),
 'height': $w.height(),
 });
});

Test the strength of the password

Registration in some sites often often require the setting of a password, the site will also be based on the input of the character characteristics of the password to give the corresponding prompt, such as password is too short, weak, moderate strength, strong and so on. How does this work? Look at the code below:


<input type="password" name="pass" id="pass" /> 
<span id="passstrength"></span>
// The following regular expressions are recommended for use on projects 
$('#pass').keyup(function(e) {
 // The password for 8 Bits and above and alphanumeric special characters 3 Items are included 
 var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");

 // The password for 7 Bits and above and alphanumeric and special characters 3 There are two of them, and the intensity is medium  
 var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
 var enoughRegex = new RegExp("(?=.{6,}).*", "g");
 if (false == enoughRegex.test($(this).val())) {
  $('#passstrength').html('More Characters');
 } else if (strongRegex.test($(this).val())) {
  $('#passstrength').className = 'ok';
  $('#passstrength').html('Strong!');
 } else if (mediumRegex.test($(this).val())) {
  $('#passstrength').className = 'alert';
  $('#passstrength').html('Medium!');
 } else {
  $('#passstrength').className = 'error';
  $('#passstrength').html('Weak!');
 }
 return true;
});

11. Redraw the size of the image using JQuery

You can redraw the image size on the server side or on the client side via JQuery.


 // To master JQuery The object's get methods   And the array of reverse Methods can be 
var arr = $('#nav').find('li').get().reverse();
$.each(arr,function(index,ele){
 .... ...
 });
0

12. Dynamically load page content while scrolling

Some sites don't load their web content once, but dynamically when the mouse scrolls down. How does this work? Look at the code below:


 // To master JQuery The object's get methods   And the array of reverse Methods can be 
var arr = $('#nav').find('li').get().reverse();
$.each(arr,function(index,ele){
 .... ...
 });
1

Here are 15 very useful jQuery code snippets that you can copy and paste directly into the code, but developers should be aware that you need to understand the code before using it.


Related articles: