10 Useful jQuery Snippets


0

In this article we will discuss 10 useful jquery snippets


Normally a list of jQuery code snippets you can smoothly add into your projects with less effort, your project is small or big, our jquery code snippets are appropriate for all projects.

The jquery code snippet snippets described in this article need the jQuery library. jQuery is a JavaScript library that makes the development of JS applications more easily, and it’s the very general JavaScript library used today, with over 79% of websites are using it. I have in person, been using it for projects for over five years, almost near the first release date back in 2006.

1. GET and POST Requests


The given code snippet will run a GET and POST request to a server using Jquery AJAX. You can comfortably make requests to your PHP web applications or any other server-side programming language with this jquery code snippet.

$.get("example.php?name=david", function(data, status) {
	// output the result to console
	console.log(data, status);
});
$.post("example.php", {
	"name": "David"
}, function(data, status) {
	// output the result to console
	console.log(data, status);
});

2. Scroll to Top

The given code snippet will scroll to the top of a page when button click, with additional animation.

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

3. Form Submit & Reset

The below given code snippet will submit a form using jQuery and reset form.

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

How to reset a form:

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

Avoid from submitting the form more than once:

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

4. Input Validation

The given code snippets will add validation to 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 must 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

The given code snippets will download a file.

Download file from a URL:

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. Avoid Right Click


The given code snippet prevents the user from right clicking your page, which is perfect if you want to stop the user from copying content, etc.

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

7. Get Widths & Heights

The given code 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

The given code snippet will check if an element exists. The most of people tend to forget, so I thought I’d pitch it in.

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

9. String Manipulation

The given code snippets will show you how to handle 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 the start and end of the string:

$("#element_id").val().trim();

Convert 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

The given code snippets will show you how you can put 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>");

Also Read: How To Disable Text Selection in HTML Using CSS & jquery?


Like it? Share with your friends!

0
Developer

0 Comments