jQuery has been successfully been used in web development to compliment HTML coding and simplify any client-side scripting. jQuery extensively simplified web developer's life and has become a leader in JavaScript available libraries.
There are lots of useful jQuery snippets available but here in this post I am going to share 30 basic and widely used code snippets that every front-end web developer must have. These are merely blank templates you can edit to change variables and parameters matching your own script. Enjoy!
1. Prevent Anchor Links From Loading
$("a").on("click", function(e){
e.preventDefault();
});
e.preventDefault();
});
I guess there are some scenario when you might want to turn-off all anchor text. This is usually implemented is comment section, especially if your site is flooded with spam comment links. With these few line snippets, all href tag will be prevent from loading.
2. Toggle Fade/Slide
// Fade
$( “.btn" ).click(function() {
$( “.element" ).fadeToggle("slow");
});
// Toggle
$( “.btn" ).click(function() {
$( “.element" ).slideToggle("slow");
});
$( “.btn" ).click(function() {
$( “.element" ).fadeToggle("slow");
});
// Toggle
$( “.btn" ).click(function() {
$( “.element" ).slideToggle("slow");
});
Sometimes we just want to hide an element on-load and makes it visible after a click. This is where jQuery toggle effect might come handy to give you that little fadeIn of slideDown touch.
3. Toggle Class on Hover
$(‘.btn').hover(function(){
$(this).addClass(‘hover’);
}, function(){
$(this).removeClass(‘hover’);
}
);
$(this).addClass(‘hover’);
}, function(){
$(this).removeClass(‘hover’);
}
);
We usually want to change the visual of an element when users hover on it, and that is what this jQuery does. It adds a class to your element when user hover on the element and remove it when the user unhover it.
4. Make Entire Div Clickable
$(".myBox").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});
window.location=$(this).find("a").attr("href");
return false;
});
The jQuery snippets above will make an entire div clickable. Looks for a link inside div with class of "myBox". Redirects to that links value when anywhere in div is clicked.
5. Check If an Image has Loaded
$(‘img’).load(function() {
console.log(‘image load successful’);
});
console.log(‘image load successful’);
});
Sometimes it is necessary to check if an image has loaded completely on the users browser. This becomes quite essential in case of Captcha.
6. Scroll to Top
// Back To Top
$('a.top').click(function(){
$(document.body).animate({scrollTop : 0},800);
return false;
});
//Create an anchor tag
<a class="top" href="#">Back to top</a>
$('a.top').click(function(){
$(document.body).animate({scrollTop : 0},800);
return false;
});
//Create an anchor tag
<a class="top" href="#">Back to top</a>
You have probable seen this functionality on most big blogs, example of these can be found on this blog (as at now), but ours is floating scroll to top button. By using the animate effect in jQuery users won’t notice the jump all at once, but instead over a brief period of milliseconds.
7. Loading External Content
$("#content").load("somefile.html", function(response, status, xhr) {
// error handling
if(status == "error") {
$("#content").html("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
// error handling
if(status == "error") {
$("#content").html("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
Believe it or not you can actually pull external HTML code from a file right into your webpage. This method is the simplest way to fetch data from the server and it doesn't require any Ajax call. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data.
8. Form Tracking with JS and Google Analytics
var array1 = [];
$(document).ready(function () {
$('input').change(function () {
var formbox = $(this).attr('id');
array1.push(formbox);
console.log("you filled out box " + array1);
});
$('#submit').click(function () {
console.log('tracked ' + array1);
//alert('this is the order of boxes you filled out: ' + array1);
_gaq.push(['_trackEvent', 'Form', 'completed', '"' + array1 + '"']);
});
});
$(document).ready(function () {
$('input').change(function () {
var formbox = $(this).attr('id');
array1.push(formbox);
console.log("you filled out box " + array1);
});
$('#submit').click(function () {
console.log('tracked ' + array1);
//alert('this is the order of boxes you filled out: ' + array1);
_gaq.push(['_trackEvent', 'Form', 'completed', '"' + array1 + '"']);
});
});
Track user interaction withyou html forms using JavaScript and Google analytics.
9. Opening Pop-ups
jQuery('a.popup').live('click', function() {</pre>
newwindow=window.open($(this).attr('href'),'','height=100,width=100');
if(window.focus) {newwindow.focus()}
return false;
});
newwindow=window.open($(this).attr('href'),'','height=100,width=100');
if(window.focus) {newwindow.focus()}
return false;
});
Although pop-up’s are quite annoying and hence they become essential when you want to grab visitors attention at all cost. Pop-up’s can be opened efficiently by using the above code.
10. Fix All Broken Images at Once
$('img').error(function(){
$(this).attr('src', ‘img/broken.png’);
});
$(this).attr('src', ‘img/broken.png’);
});
Occasionally, there are times when we have broken image links on our website and replacing them one after the other will be time consuming, so adding this simple jQuery snippets can save you a lot of time.
11. Equal Column Height
var maxheight = 0;
$("div.col").each(function(){
if($(this).height() > maxheight) { maxheight = $(this).height(); }
});
$("div.col").height(maxheight);
$("div.col").each(function(){
if($(this).height() > maxheight) { maxheight = $(this).height(); }
});
$("div.col").height(maxheight);
The snippet above will check every div with class "col" and see which one contains the highest size, once done it will apply that height to all divs with class col.
Example:
<div style="height:200px;" class="col"></div><!-- this being the higher div will be set as the max_height -->
<div class="col"></div><!-- this being the smaller div will be made 200px high -->
<div class="col"></div><!-- this being the smaller div will be made 200px high -->
While this is not the most recommended solution for your layout display, this code snippet may come in handy down the line. Unfortunately, CSS does not support this natively, sometimes when creating column based layouts it will be so much better if the columns are aligned by height.
12. Reloading iframes
$('iframe').attr('src', $('iframe').attr('src'));
In a scenario where multiple iframes need to be loaded we have a jQuery snippet at our disposal
13. Keystroke Events
$('input').keydown(function(e) { // variable e contains keystroke data // only accessible with .keydown() if(e.which == 11) { e.preventDefault(); } }); $('input').keyup(function(event) { // run other event codes here });
The jQuery keydown and keyup event listeners are perfect for dealing with users input. The keydown event is sent to an element when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus.
14. Password Strength
$('#pass').keyup(function(e) {
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
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;
});
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
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;
});
Many sites that require login credentials enforce a security setting often referred to as password complexity requirements. These requirements ensure that user passwords are sufficiently strong and cannot be easily broken. Password’s strength include it’s length, complexity, and unpredictability. The above code will pop-up concerning users input strength.
15. Disabling Input Fields
$('input[type="submit"]').attr("disabled", true);
There are some occasion where you might want to disable the submit button of a form until user perform a certain action like (checking "I've read terms and conditions" button.) To enable the function back, just run removeAttr function on the input with disabled as the parameter:
$('input[type="submit"]').removeAttr("disabled");
16. Traversing the DOM
$("div#home").prev("div"); // find the div previous in relation to the current div
$("div#home").next("ul"); // find the next ul element after the current div
$("div#home").parent(); // returns the parent container element of the current div
$("div#home").children("p"); // returns only the paragraphs found inside the current div
$("div#home").next("ul"); // find the next ul element after the current div
$("div#home").parent(); // returns the parent container element of the current div
$("div#home").children("p"); // returns only the paragraphs found inside the current div
The goal of this snippet is to pull data from another element related to the currently active element(clicked, hovered, etc). This could be the container(parent) element or another inner(child) element. I guess only the advance jQuery developers can understand this topic, but there is no barrier in experimenting.
17. Browser Detection
//safari browser
if($.browser.safari)$(“#menu li a”).css(“padding”, “1em 1.2em”);
//IE 5 and above
if($.browser.msie && $.browser,version >5) $(“#menu li a”).css(“padding”, “1em 1.2em”);
//Firefox
If($.browser.mozilla) $(“#menu li a”).css(“padding”, “1em 1.2em”);
if($.browser.safari)$(“#menu li a”).css(“padding”, “1em 1.2em”);
//IE 5 and above
if($.browser.msie && $.browser,version >5) $(“#menu li a”).css(“padding”, “1em 1.2em”);
//Firefox
If($.browser.mozilla) $(“#menu li a”).css(“padding”, “1em 1.2em”);
It is very often that we need to determine the users browser. The $.browser property provides information about the web browser that is accessing the page, as reported by the browser itself.
18. Partial Page Refresh
setInterval(function() {
$("#class-id").load(location.href+" #class-id>*","");
}, 2000); // seconds to wait
$("#class-id").load(location.href+" #class-id>*","");
}, 2000); // seconds to wait
We might need to refresh a page partially instead of refreshing the whole page. It is a very useful and bandwidth saving feature that jQuery provides. You don't need any ajax, just apply an id to a certain element, run this little script, and choose how many seconds to wait until refresh.
19. Append New HTML
var sometext = "Say something awesome";
$("p#sample1").append(sometext); // added after
$("p#tsample1").prepend(sometext); // added before
$("p#sample1").append(sometext); // added after
$("p#tsample1").prepend(sometext); // added before
With the .append() method we can quickly place any HTML code directly into the DOM. .append() also supports passing in multiple arguments as input. Supported input includes DOM elements, jQuery objects, HTML strings, and arrays of DOM elements.
20. setInterval and setTimeout
var timer = setInterval(function(){ if(someConditionIsTrue){ clearTimeout(timer); } },100); /*But if, due to some reasons, the 'someCondition' never gets true than you need to clear the timer otherwise it might turn into an infinite loop*/ setTimeout("clearTimeout(timer)",10000) //10 seconds or more
setTimeout() in general can be compared to a countdown timer. It’s used to execute a certain function at the end of given time.
setInterval() in general can be compared to an alarm that strikes after a particular time, It repeats itself at regular time that is passed to this function.
21. Zebra Stripped Unordered List
$('li:odd').css('background', '#DDDDDD');
With this little snippet you can easily create zebra striped unordered lists. It will place the background you define on every odd list item so that you can place the default one for the even ones in your CSS file.You can add this snippet to any type of markup like tables, plain divs or anything at all.
22. Open All External Links in New Window
$('a').each(function() {
var a = new RegExp('/' + [removed].host + '/');
if(!a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank');
});
}
});
var a = new RegExp('/' + [removed].host + '/');
if(!a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank');
});
}
});
Tired of attributing all external links with target="_blank"? This jQuery snippets will help you solve that headache.
23. Enabling Submit Function If Text Entered
$('#username').keyup(function() {
$('#submit').attr('disabled', !$('#username').val());
});
$('#submit').attr('disabled', !$('#username').val());
});
When surfing the web, i found this jQuery snippet and thought most other developers will find this so useful. The code ensures that the submit button is only enabled if the "username" input field is not empty (you can see such a behavior on twitter for example).
24. jQuery Cookies set/get/delete
//get cookie
function getCookie( name ) {
var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
return null;
}
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ';', len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}
//set cookie
function setCookie( name, value, expires, path, domain, secure ) {
var today = new Date();
today.setTime( today.getTime() );
if ( expires ) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );
document.cookie = name+'='+escape( value ) +
( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
( ( path ) ? ';path=' + path : '' ) +
( ( domain ) ? ';domain=' + domain : '' ) +
( ( secure ) ? ';secure' : '' );
}
//delete cookie
function deleteCookie( name, path, domain ) {
if ( getCookie( name ) ) document.cookie = name + '=' +
( ( path ) ? ';path=' + path : '') +
( ( domain ) ? ';domain=' + domain : '' ) +
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
function getCookie( name ) {
var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
return null;
}
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ';', len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}
//set cookie
function setCookie( name, value, expires, path, domain, secure ) {
var today = new Date();
today.setTime( today.getTime() );
if ( expires ) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );
document.cookie = name+'='+escape( value ) +
( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
( ( path ) ? ';path=' + path : '' ) +
( ( domain ) ? ';domain=' + domain : '' ) +
( ( secure ) ? ';secure' : '' );
}
//delete cookie
function deleteCookie( name, path, domain ) {
if ( getCookie( name ) ) document.cookie = name + '=' +
( ( path ) ? ';path=' + path : '') +
( ( domain ) ? ';domain=' + domain : '' ) +
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
jQuery can be used to manipulate browser cookies and this little demonstration shows you how to create, access and remove cookies.
25. Select/Deselect All options
<!-- jQuery -->
$('.SelectAll').live('click', function(){
$(this).closest('.divAll').find('input[type=checkbox]').attr('checked', true);
return false; });
$('.DeselectAll').live('click', function(){
$(this).closest('.divAll').find('input[type=checkbox]').attr('checked', false);
return false; });
<!-- HTML -->
<div class="divAll"> <a href="#" class="SelectAll">Select All</a>
<a href="#" class="DeselectAll">Deselect All</a> <br /> \
<input type="checkbox" id="Lahore" /><label for="Lahore">Lahore</label>
<input type="checkbox" id="Karachi" /><label for="Karachi">Karachi</label>
<input type="checkbox" id="Islamabad" /><label for="Islamabad">Islamabad</label> </div>
$('.SelectAll').live('click', function(){
$(this).closest('.divAll').find('input[type=checkbox]').attr('checked', true);
return false; });
$('.DeselectAll').live('click', function(){
$(this).closest('.divAll').find('input[type=checkbox]').attr('checked', false);
return false; });
<!-- HTML -->
<div class="divAll"> <a href="#" class="SelectAll">Select All</a>
<a href="#" class="DeselectAll">Deselect All</a> <br /> \
<input type="checkbox" id="Lahore" /><label for="Lahore">Lahore</label>
<input type="checkbox" id="Karachi" /><label for="Karachi">Karachi</label>
<input type="checkbox" id="Islamabad" /><label for="Islamabad">Islamabad</label> </div>
Using the above jQuery code you can easily create a checkbox for selecting and deselecting options in a webpage.
26. Limiting MaxLength for TextArea
<!-- jQuery -->
var MaxLength = 500;
$('#txtDescription').keypress(function(e)
{
if ($(this).val().length >= MaxLength) {
e.preventDefault();}
});
<!-- HTML -->
<asp:TextBox ID="txtDescription" runat="server"
TextMode="MultiLine" Columns="50" Rows="5"></asp:TextBox>
var MaxLength = 500;
$('#txtDescription').keypress(function(e)
{
if ($(this).val().length >= MaxLength) {
e.preventDefault();}
});
<!-- HTML -->
<asp:TextBox ID="txtDescription" runat="server"
TextMode="MultiLine" Columns="50" Rows="5"></asp:TextBox>
You might want to put a textarea on a form and validate maximum number of characters user can enter in it. With the code above, you can do that with ease.
27. Resize Image Proportionally
(function($) {
$.fn.imageResize = function(options) {
var that = this;
var settings = {
width: 150,
height: 150
};
options = $.extend(settings, options);
if (!that.is('img')) {
return;
}
return that.each(function() {
var maxWidth = options.width;
var maxHeight = options.height;
var ratio = 0;
var width = $(that).width();
var height = $(that).height();
if (width > maxWidth) {
ratio = maxWidth / width;
$(that).css('width', maxWidth);
$(that).css('height', height * ratio);
}
if (height > maxHeight) {
ratio = maxHeight / height;
$(that).css('height', maxHeight);
$(that).css('width', width * ratio);
}
});
};
})(jQuery);
$.fn.imageResize = function(options) {
var that = this;
var settings = {
width: 150,
height: 150
};
options = $.extend(settings, options);
if (!that.is('img')) {
return;
}
return that.each(function() {
var maxWidth = options.width;
var maxHeight = options.height;
var ratio = 0;
var width = $(that).width();
var height = $(that).height();
if (width > maxWidth) {
ratio = maxWidth / width;
$(that).css('width', maxWidth);
$(that).css('height', height * ratio);
}
if (height > maxHeight) {
ratio = maxHeight / height;
$(that).css('height', maxHeight);
$(that).css('width', width * ratio);
}
});
};
})(jQuery);
You do not need to worry about the image size and resolution when uploading the same into the website. jQuery have offer you a code for image resizing.
28. Validating an Email Address
<!-- jQuery -->
$('#txtEmail').blur(function(e) {
var sEmail = $('#txtEmail').val();
if ($.trim(sEmail).length == 0) {
alert('Please enter valid email address');
e.preventDefault();
}
var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]
{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
alert('Valid Email');
}
else {
alert('Invalid Email');
e.preventDefault();
}
});
<!-- HTML -->
<asp:TextBox id="txtEmail" runat="server" />
$('#txtEmail').blur(function(e) {
var sEmail = $('#txtEmail').val();
if ($.trim(sEmail).length == 0) {
alert('Please enter valid email address');
e.preventDefault();
}
var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]
{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
alert('Valid Email');
}
else {
alert('Invalid Email');
e.preventDefault();
}
});
<!-- HTML -->
<asp:TextBox id="txtEmail" runat="server" />
This is a very basic functionality to validate the email address. If an invalid email is entered, it will alert "Valid Email", else it returns "Invalid Email"
29. Print Page Option
<!-- jQuery -->
$('a.printPage').click(function(){
window.print();
return false;
});
<!-- HTML -->
<div>
<a class="printPage" href="#">Print</a>
</div>
$('a.printPage').click(function(){
window.print();
return false;
});
<!-- HTML -->
<div>
<a class="printPage" href="#">Print</a>
</div>
Providing option to print a page is a common task for web developers. Typically you would create a special print template, open it in a popup and then call window.print().This plugin take the page you want to print, put it in an iframe and print it without the need of a popup.
30. Input Field/Swap Input Field
<!-- jQuery -->
$('input[type=text]').focus(function(){
var $this = $(this);
var title = $this.attr('title');
if($this.val() == title)
{
$this.val('');
}
}).blur(function() {
var $this = $(this);
var title = $this.attr('title');
if($this.val() == '')
{
$this.val(title);
}
});
<!-- HTML -->
<div>
<input type="text"
name="searchCompanyName"
value="Company Name"
title="Company Name" />
</div>
$('input[type=text]').focus(function(){
var $this = $(this);
var title = $this.attr('title');
if($this.val() == title)
{
$this.val('');
}
}).blur(function() {
var $this = $(this);
var title = $this.attr('title');
if($this.val() == '')
{
$this.val(title);
}
});
<!-- HTML -->
<div>
<input type="text"
name="searchCompanyName"
value="Company Name"
title="Company Name" />
</div>
We normally display some default text inside it (e.g "Enter Address Here", "Search Here" "Company Name" etc.) and when user click on it, text disappears and user can enter the value for it. That's what the code does.
Conclusion
These are the pieces of jQuery snippets I find myself using again and again in my projects. Feel free to use any of the code in your projects or save this article to your own bookmarks as a reference. As usual, your thoughts are always welcome.
Subscribe For Free Updates!
*Please confirm the email sent to your inbox after clicking "Sign Up!".
great work
ReplyDeleteT20 WC 2016
Bedava lig tv izle, Ücretsiz online Lig tv canlı izle. Türk Super Lig için bedava online izle lig tv canlı izle . Türk Super Lig için bedava online izle Lig tv canlı izle.
ReplyDeleteCouldn't agree more. jQuery extensively simplified web developer's life and has become a leader in JavaScript available libraries. spanish to english
ReplyDelete