Irrespective of whether you’re a beginner or a professional coder, there are plenty of jQuery code snippets available over the web that you may tend to use, time and again. In this post, I’ve put together some useful and widely-used code snippets that a front-end web developer must be aware of.
Also Read: 15 Best jQuery Plugins to Make Responsive Design Easier
Load external content
Do you want to load external content from some other domain? That’s possible with jQuery. Put it simply, you can break the cross-domain barrier with help of jQuery, as illustrated in the following code:
$("#content").load("fileoutside.html", function(response, status, my) { // error handling if(status == "error") { $("#content").html("An error occured: " + my.status + " " + my.statusText); } });
Back to top button
You may have stumbled upon dozens of websites that contains a “back to top button”. This is a very useful button that facilitate users with smooth scrolling back to the top of the web page. You can add this button on your own, using the following jQuery code snippet:
// Back To Top $('a.up').click(function(){ $(document.body).animate({scrollTop : 0},875); return false; }); //Create an anchor tag <a class=”up” href=”#”>Go to Top</a>
Swap Input Field
Every website comes with certain input text fields. We usually add default text in the fields to help users know what they’re meant for. For example, you may have some input field with “Name” as your default text, and the text disappears when the field is being clicked by a user. Here’s a simple jQuery code that lets you swap the input field with some other text field.
<div> <input type="text" name="MyInputField" value="JobTitle" title="Job" /> </div>
Disabling input fields
Other than swapping input field values, you may at several occasions would want some of the text field to be disabled until a user completes a certain action. Below is a line of code that will help you add a disabled attribute to your input field:
$('input[type="submit"]').attr("disabled", true); Now, in order to enable the disabled attribute, use the following line of code: $('input[type="submit"]').removeAttr("disabled”);
On Hover add and Remove a class
We often want to change the visual of the clickable element present on our page, when the user hovers over it. For instance, you may wish to add a cool hover on a div. Sadly, there are some browsers that doesn’t allow such functionality to be embedded with pure CSS. However, below is a simple jQuery code that allows you to do so:
view plaincopy to clipboardprint? $('.onhover').hover( function(){ $(this).addClass('hover_class') }, function(){ $(this).removeClass('hover_class') } )
Disabling Right-click
Many web developers often choose to disable right-click functionality on certain web pages. You can do it yourself with help of the following code:
<!-- jQuery: Disabling Right Click --> $(document).bind("contextmenu",function(e){ e.preventDefault(); });
Fix broken images automatically
There will be times, when you will notice broken image links on your website. In that case, we often have to replace them one by one. But that can be a daunting and time-consuming task. However, adding the following code can save you from going through a lot of hassle:
$('img').error(function(){ $(this).attr('src', ‘img/default.jpg’); });
Note: Even though, you don’t have any broken links in your site, adding the above code won’t do any harm.
Validating an email
One of the most common task that we often carry out on a HTML form is validating an email address, as demonstrated in the following example:
<!-- jQuery: Validating an email. --> $('#txtEmail').blur(function(e) { var sEmail = $('#txtEmail').val(); if ($.trim(sEmail).length == 0) { alert('Enter valid Email ID'); 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('Email not valid'); e.preventDefault(); } }); <!-- HTML: Validating an email--> <asp:TextBox id="txtEmail" runat="server" />
Open external links in a new tab/window
The target=”blank” attribute force open links in a new tab/window. This feature proves useful in case you need to open up external links in a new tab or window. However, same domain links should be opened in the same window only. Below is a code that will help detect if a link is external, if the conditional value is “true”, then the code will add a target=”blank” attribute to it.
$('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.no-link').click(function(e){ e.preventDefault(); });
Don’t want links to open up in another page or want to avoid reloading them, in that case the above piece of code will prove useful to you.
Wrapping Up!
I hope that the aforementioned list of jQuery code snippets would prove useful to you, and help reduce your development time.
Author Bio
Jason Roiz is an innovative and experimental veteran developer, who now devote his time in advising its clients to hire Magento developer. He is also associated with OSSMedia Ltd., a CMS development company giving proficient WordPress, Magento, Drupal and Joomla improvement administrations.