5 Useful jQuery Snippets
1. Back to Top Button
$('a.top').click(function(){
$(document.body).animate({scrollTop : 0},800);
return false;
});
This code can be used to create a smooth, simple back to top button — a trendy and functional item to have on any website. Just make sure you use this HTML code or something similar (with the a tag having a class of “top”) to create the actual button: <a class=”top” href=”#”>Back to top</a>
2. Enabling/Disabling Input Fields
$('input[type="submit"]').attr("disabled", true);
$(‘input[type="submit"]').removeAttr("disabled”);
For when you don’t want a user to be able to input to a certain field or submit a form (maybe at all, maybe until they’ve filled out some prerequisite info). The top line of code will disable an input element, and the bottom line will enable it.
3. Zebra Striping
$('li:odd').css('background', ‘#e7e7e7’);
Zebra striping is a common stylistic choice often seen in lists and tables. The code above will add zebra striping to a list.
4. Prevent Link Functionality
$(“a.disable").on("click", function(e){
e.preventDefault();
});
The code snippet above will take away all functionality from a link. Whichever link you place in the selector will not work at all when a user clicks it. Just make sure you specify which link you want to not work, otherwise you could accidentally end up disabling all your links by mistake.
5. Toggle Classes
$(“.main”).toggleClass(“selected”);
This snippet is super useful for changing the styling, appearance, and possibly even functionality of an HTML element by adding or removing a particular class to it. Great to use as a result of a click trigger.