HTML CSS JavaScript jQuery PHP MySQL

20 Useful jQuery Snippets

Updated on by David Adams

20 Useful jQuery Snippets

These snippets are the most common snippets you will see in most websites created today, all on one page for you to copy and paste into your projects.

These snippets require the jQuery library, jQuery makes the development of JavaScript applications easier and it's the most popular JavaScript library used today, I've been using it for projects for the past 10 years, almost back near its initial release date in 2006.


1. GET and POST Requests

This snippet will make GET and POST requests to a server, you can easily make requests to your PHP applications or any other server-side programming language with this snippet.

$.get("example.php?name=dave", function(data, status) {
	console.log(data, status);
});
$.post("example.php", {
	"name": "dave"
}, function(data, status) {
	console.log(data, status);
});

2. Scroll to Top

This snippet will scroll to the top of a page with a click of a button, with added animation.

$(".scrolltotop").click(function(e) {
	e.preventDefault();
    $("html").animate({ scrollTop: 0 }, "slow");
});

3. Form Submit & Reset

This snippet will submit a form using jQuery.

$("#form_id")[0].submit();

How to reset a form:

$("#form_id")[0].reset();

Prevent from submitting the form more than once:

$("#form_id")[0].submit(function(e) {
	$("#form_id")[0].submit(function(e) {
    	return false;
    });
});

4. Input Validation

These snippets will use validation for your input fields.

Email validation:
if (/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test($("#email").val())) {
	console.log("Input field has valid email!");
}

Length validation:
if ($("#password").val().length < 5 || $("#password").val().length > 15) {
	console.log("Password needs to be between 5 and 15 characters long.");
}

Username validation:
if (!/^[a-zA-Z0-9]+$/.test($("#username").val())) {
	console.log("Username must contain only numbers and characters.");
}

5. Download File

These snippets will download a file.

Download URL file:
var element = document.createElement("a");
element.setAttribute("href", "https://codeshack.io/web/img/codeshack.png");
element.setAttribute("download", "codeshack.png");
document.body.appendChild(element);
element.click();

Download textarea text:
var element = document.createElement("a");
element.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURIComponent($("#textarea").val()));
element.setAttribute("download", "textarea-text.txt");
document.body.appendChild(element);
element.click();

6. Prevent Right Click

This snippet prevents a user from right clicking your page, this is ideal if you want to stop the user from copying content etc.

$(document).bind("contextmenu", function(e) {
	return false;
});

7. Get Widths & Heights

These snippets will get the width and height of elements.

Browser view-port:
$(window).width();
$(window).height();

HTML Document:
$(document).width();
$(document).height();

Specific element:
$("#element_id").width();
$("#element_id").height();

Screen size:
screen.width;
screen.height;

8. Check if Element Exists

Most people forget how to check if an element exists so I thought I'd add this one in.

if ($("#element_id").length) {
	console.log("Element exists...");
} else {
	console.log("Element does not exists...")
}

9. String Manipulation

These snippets will show you how to manipulate strings.

Replace a word:
$("#element_id").val().replace("Dave", "David");

Case sensitivity:
$("#element_id").val().toLowerCase();
$("#element_id").val().toUpperCase();

String length:
$("#element_id").val().length;

Remove white-spaces from each end of the string:
$("#element_id").val().trim();

Split a string to an array:
$("#element_id").val().split(" ");

Check if a string contains another string:
$("#element_id").val().contains("dave");

10. Add Items to List

These snippets will show you how can you add items to your lists, tables, etc.

Add item to list:
$("ul").append("<li>List Item " + $("ul li").length + "</li>");

Add item to table:
$("table").append("<tr><td>item 1</td><td>item 2</td></tr>");

Add item to the start of a list:
$("ul").prepend("<li>List Item " + $("ul li").length + "</li>");

11. Check if Element is Visible or Hidden

This snippet will show you how to check if an element is hidden or visible.

if ($("#element_id").is(":visible")) {
	console.log("Element is visible...");
} else {
	console.log("Element is hidden...");
}

12. Get the Selected Radio Button

This snippet will show you how to get the selected radio button.

$("#form_id input[type='radio']:checked").val();

13. Check if Checkbox is Checked

This snippet will check if a checkbox is checked.

if ($("#element_id").is(':checked'))) {
	console.log("Checkbox is checked...");
} else {
	console.log("Checkbox is not checked...");
}

14. Get IP Address

This snippet will show you how to get the IP address of the client.

$.get('http://jsonip.com', function(data) {
	console.log(data.ip);
});

15. Countdown in Seconds

This snippet will countdown in seconds.

var countdown = setInterval(function() {
	var num = parseInt($("#countdown").text());
    if (num == 0) {
    	clearInterval(countdown);
    } else {
    	$("#countdown").text(num - 1)
    }
}, 1000);

16. Copy Text from Textarea

This snippet will select and copy text from a textarea.

$("textarea").select();
document.execCommand('copy');

17. Detect Mobile Device

This snippet will detect if the visitor is using a mobile device.

if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
	console.log("This device is a mobile.");
}

18. Redirect Page after Specific Time

This snippet will redirect the document page after 5 seconds.

window.setTimeout(function() {
	window.location.href = "http://www.google.com";
}, 5000);

19. Refresh Page

This snippet will reset the current page.

location.reload();

20. Selecting Elements with Data Attribute

These snippets will show you how to select elements that contain the data attributes.

Select all elements containing the attribute data-myattr:
$('[data-myattr]');

Select all elements containing the attribute data-myattr and value dave:
$('[data-myattr="dave"]');


Conclusion

That's basically my list of goto snippets for my projects that require jQuery, feel free to share the snippets and this post, this will help our website become more popular and thus more content.

If I've missed any important snippets then feel free to drop a comment, I'll probably write another article that will contain more snippets.