📜 ⬆️ ⬇️

10+ useful jQuery snippets for every day



Over the years, the jQuery library has become an integral part of the work of every web developer. After all, it is easy to use, fast and has very wide opportunities. In this article, I have compiled a list of more than ten snippets that you can freely take for use. They are very easy to adapt to the needs of your own projects.


Smooth scroll to top of page


Let's start this list with a very popular and useful snippet: these 4 lines of code will allow your visitors to smoothly scroll the page to the top by simply clicking the link (with id #top) at the bottom of the page.
')
$("a[href='#top']").click(function() { $("html, body").animate({ scrollTop: 0 }, "slow"); return false; }); 

A source

Duplicate thead to the bottom of the html table


For better readability of the tables, it would be nice to copy the table header to the bottom of the table. Actually, this is what the next snippet does.

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

A source

Loading external content


Need to add some external content to the div? So this is very easy to do with jQuery, as shown in the example below.

 $("#content").load("somefile.html", function(response, status, xhr) { // error handling if(status == "error") { $("#content").html("An error occured: " + xhr.status + " " + xhr.statusText); } }); 

A source

Columns of the same height


In the case of using columns to display the content of your site, it will definitely look better if the columns have the same height. The code below will take all div elements with the class .col and set their height to the highest element. Super helpful!

 var maxheight = 0; $("div.col").each(function() { if($(this).height() > maxheight) { maxheight = $(this).height(); } }); $("div.col").height(maxheight); 

A source

Table stripes (zebra)


When the data is displayed in a table, the differing colors in each row unambiguously increase readability. Here is a snippet for automatically adding a CSS class to every other (even) row of the table.

 $(document).ready(function(){ $("table tr:even").addClass('stripe'); }); 

A source

Partial page refresh


If you need to update only part of the page, then these 3 lines of code will definitely help. In the example div, id #refresh is automatically updated every 10 seconds.

 setInterval(function() { $("#refresh").load(location.href+" #refresh>*",""); }, 10000); // milliseconds to wait 

A source

Preload images


jQuery simplifies the preloading of images in the background, so that visitors do not have to wait for ages when the desired images appear. The code is ready to use, just edit the list of images in line 8.

 $.preloadImages = function() { for(var i = 0; i<arguments.length; i++) { $("<img />").attr("src", arguments[i]); } } $(document).ready(function() { $.preloadImages("hoverimage1.jpg","hoverimage2.jpg"); }); 

A source

Opening external links in a new window or new tab


The target attribute = "_ blank" allows you to open links in new windows. But this refers to the opening of external links, intradomain links should open in the same window.
This code finds the external link and adds the attribute target = "_ blank" to the element found.

 $('a').each(function() { var a = new RegExp('/' + window.location.host + '/'); if(!a.test(this.href)) { $(this).click(function(event) { event.preventDefault(); event.stopPropagation(); window.open(this.href, '_blank'); }); } }); 

A source

Viewport width / height div


This handy code snippet allows you to create a div. Stretched in width / height viewport. The code also supports resizing the window. Perfect solution for modal dialogs and popup windows.

 // global vars var winWidth = $(window).width(); var winHeight = $(window).height(); // set initial div height / width $('div').css({ 'width': winWidth, 'height': winHeight, }); // make sure div stays full width/height on resize $(window).resize(function(){ $('div').css({ 'width': winWidth, 'height': winHeight, }); }); 

A source

Password complexity check


When you provide users with an independent password choice, it would be nice to show how complex their password is. The snippet code does just that.

First, create the input fields:

 <input type="password" name="pass" id="pass" /> <span id="passstrength"></span> 


And then a little jQuery code. The entered password will be checked using regular expressions and based on this, the user will be prompted to find out how complex his password is.

 $('#pass').keyup(function(e) { var strongRegex = new RegExp("^(?=.{8,})(?=.*[AZ])(?=.*[az])(?=.*[0-9])(?=.*\\W).*$", "g"); var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[AZ])(?=.*[az]))|((?=.*[AZ])(?=.*[0-9]))|((?=.*[az])(?=.*[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; }); 

A source

Image resizing


Of course, you can resize your images on the server side (for example, using PHP and the GD library), but sometimes it is useful to do it on the client side using jQuery. Here is a snippet for this.

 $(window).bind("load", function() { // IMAGE RESIZE $('#product_cat_list img').each(function() { var maxWidth = 120; var maxHeight = 120; var ratio = 0; var width = $(this).width(); var height = $(this).height(); if(width > maxWidth){ ratio = maxWidth / width; $(this).css("width", maxWidth); $(this).css("height", height * ratio); height = height * ratio; } var width = $(this).width(); var height = $(this).height(); if(height > maxHeight){ ratio = maxHeight / height; $(this).css("height", maxHeight); $(this).css("width", width * ratio); width = width * ratio; } }); //$("#contentpage img").show(); // IMAGE RESIZE }); 

A source

Automatic content download by scroll


Some sites, such as Twitter, download content by scrolling. This means that all content is dynamically loaded on the page in the process of scrolling down.
Here is an example of how you can make this effect on your site.

 var loading = false; $(window).scroll(function(){ if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){ if(loading == false){ loading = true; $('#loadingbar').css("display","block"); $.get("load.php?start="+$('#loaded_max').val(), function(loaded){ $('body').append(loaded); $('#loaded_max').val(parseInt($('#loaded_max').val())+50); $('#loadingbar').css("display","none"); loading = false; }); } } }); $(document).ready(function() { $('#loaded_max').val(50); }); 

A source

Check if image is loaded


Here is a snippet that I often use when working with images, because this is the best way to find out if the image is loaded or not.

 var imgsrc = 'img/image1.png'; $('<img/>').load(function () { alert('image loaded'); }).error(function () { alert('error loading image'); }).attr('src', imgsrc); 

A source

Sort the list in alphabetical order


In some cases, sorting a long list in alphabetical order is very useful. This snippet takes any list and sorts it.

 $(function() { $.fn.sortList = function() { var mylist = $(this); var listitems = $('li', mylist).get(); listitems.sort(function(a, b) { var compA = $(a).text().toUpperCase(); var compB = $(b).text().toUpperCase(); return (compA < compB) ? -1 : 1; }); $.each(listitems, function(i, itm) { mylist.append(itm); }); } $("ul#demoOne").sortList(); }); 

A source

Source: https://habr.com/ru/post/211538/


All Articles