jQuery Code Snippets for your Future Project

Code snippets are handy and very useful. They do the job for you without much effort. Hold onto these snippets to use for your next project.

  • Change button text when clicked:

[javascript]
$(document).ready(function(){
$(".button").click(function(){
$(this).val("Some other text");
});
});
[/javascript]

  • Mark external links with an icon

[javascript]
$('a').each(function(){
if(this.hostname != location.hostname){
$(this).append('<img src="external.png" />')
.attr('target','_blank');
}
});
[/javascript]

  • Change DIV background color randomly

[javascript]
$(document).ready(function() {
changeColor();
});

function changeColor() {
var rndColors = ["#00FF00", "#CCCCCC", "#995499", "#FFFFFF", "#FF9900"];
var selColor = Math.floor(Math.random() * rndColors.length);
$('div').css("background-color", rndColors[selColor]);
setTimeout(changeColor, 1000);
}
[/javascript]

  • Smooth scrolling to top of the page

[javascript]
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
[/javascript]

  • Check if file exists on server using jQuery

[javascript]
$('#btnSubmit).click(function () {
$.ajax({
url: $('#txtUrl').val(),
success: function (data) {
alert('File Exists!!!!!');
},
error: function (data) {
alert('File does not exist!!!!');
}
});
});
[/javascript]

  • Check for working internet connection

[javascript]
function checkInternet() {
var status = navigator.onLine;
if (status) {
alert("Working");
} else {
alert("Not Working ");
}
}
[/javascript]

Call this function on click of button:

[javascript]
<input type="button" value="Check Connection" onclick="checkInternet()" />
[/javascript]

  • Prevent right click

[javascript]
$(function(){
$(document).on("contextmenu",function(e){
e.preventDefault();
});
});
[/javascript]