jQuery and JavaScript snippets

· Leave a comment · in JavaScript, jQuery

This is a list of useful snippets that do not garner their own posts.

The jQuery snippets have been tested with version 1.7.2+.

If you have any to contribute, email them to me and I will post them!

Append a .js file to a page (JavaScript)
The best way to append a js file is to do it with JavaScript. Keep in mind that any code not enclosed will run when appended.

Tested in:
Firefox 3.6+, IE8+, iOS

var _sObj = document.createElement('script');
_sObj.src = '/js/IE8.js';
_sObj.type  = "text/javascript";
document.body.appendChild(_sObj);

Detect a keypress (jQuery)
This example detects a keypress of the “ESC” and “ENTER” keys on the document. You can modify the $(document) call to be a specific object, for example a radio button.

Tested in:
Firefox 3.6+, IE8+, iOS

$(document).on("keydown",function(event) {
	if(event.which === 27){ //esc
		//do something
	}
	if(event.which === 13){ //enter
		//do something
	}
});

Total number of elements on a page (jQuery)
Tested in:
Firefox 3.6+, IE8+, iOS

$("*").length

Generate a unique random number (JavaScript)
This function returns a unique random number when called. Initially, there is a decimal but it is removed.

Tested in:
Firefox 3.6+, IE8+, iOS

function randomNumber(){
    var rnNow=new Date();
    var rn = rnNow.getTime().toString().split(".").join(""); //milliseconds > to string > remove decimal
    var rn = parseFloat(rn); //back to number
	var rn = Math.floor(Math.random() * rn + 1);
    return rn;
}

Convert string to a number (JavaScript)
parseFloat - this one is so damn simple but incredibly useful, I use it all the time. Great for converting say “728px” to 728.

Tested in:
Firefox 3.6+, IE8+, iOS

var _n = parseFloat("728px");

Reset select dropdown on page refresh (jQuery)
Ever refresh a page but the dropdown doesn’t go back to the first selection – like it should? Using the following code on page load solves the problem.

Tested in:
Firefox 3.6+, IE8+, iOS

$(".dropdown-select-element")
    .find("option:first")
    .attr("selected","selected");

Preload images (jQuery)
Code for preloading a single image or multiple images. If you are familiar with Firebug “Console”, you can run the code there and see that the image(s) loads under Firebug’s “Net” > “Images” section.

Tested in:
Firefox 3.6+, IE8+, iOS

//single
window["myImg"] = $('<img />').attr('src','some_image.jpg');

//multiple
var _imgArray = ["img/image1.jpg","img/image2.jpg"];
$.each(_imgArray,function(index,value){
	window["myImg"+index] = $('<img>').attr('src',value);
});

Remove characters with regex (JavaScript)
I love regex – no, wait – I hate regex – no, wait…
Remove any characters from a string except a-z, A-Z, 0-9 or a space.

Tested in:
Firefox 3.6+, IE8+, iOS

someString = someString.replace(/[^a-zA-Z 0-9]+/g,'');

Adding multiple attributes with one call (jQuery)
Instead of executing multiple .attr() calls on an element, you can add all the attributes in just one call.
Really useful if you have set up default settings for elements. You can pass settings using a name:value pair format.

Tested in:
Firefox 3.6+, IE8+, iOS

_defaultSettings = {"data-has-focus":"true","data-index":1};
$("#some-element").attr(_defaultSettings);

Access an element using a dynamic identifier (jQuery)
Sometimes you only have an id or class name without the “#” or “.” included. This is the simple way to access the element using that value. You append a “#” or “.” to the beginning of the value.

Tested in:
Firefox 3.6+, IE8+, iOS

var elemId = "site-info";
var elemClass = "site-info-module";
$("#"+elemId).css("color","red");
$("."+elemClass).css("color","blue");

Verifying an element exists (JavaScript/jQuery)
With JavaScript you can use getElementById – but it’s easier to use jQuery since you can test for existence on any element.

Tested in:
Firefox 3.6+, IE8+, iOS

//JavaScript
var e = document.getElementById("some-element");
if( typeof(e) !== 'undefined' && e !== null ){
    //exists
}

//jQuery
if( $("#some-element").length > 0 ){ //by id 
    //exists
}
if( $(".some-element").length > 0 ){ //by class
    //exists
}
if( $("ul").length > 0 ){ //by tag
    //exists
}

Centering an element (jQuery)
Create a jQuery function and call it on an element. Great for overlays.

Tested in:
Firefox 3.6+, IE8+, iOS

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}
 
//Call the above function on an element
$(".test").center();

Apply a style to every element on a page (jQuery)

Tested in:
Firefox 3.6+, IE8+, iOS

$("*").css("outline","1px dotted #00bfff");

Abort JavaScript (JavaScript)
Say you want to repurpose some JS code and copy an entire .js file over to a directory. Now you want to keep the code in the file for reference, adding new code above it. But how to stop the code below from executing? You can use console or return false; – but there is another way. You can throw a customized error using only JavaScript.

Tested in:
Firefox 3.6+, IE8+, iOS

(function(){
   throw new Error('This is an error thrown to abort javascript');
})();

Get domain (JavaScript)
To get the domain we usually use document.domain, but when used on localhost or 127.0.0.1 that has a port number, the port number is ignored. So a domain of localhost:2000 would only return localhost.

You need to use document.location.host, which returns the domain and port number.

The following code would return http://localhost:2000 using the above example.

Tested in:
Firefox 3.6+, IE8+, iOS

var _domain = document.location.protocol + "//" + document.location.host

Great books are available on JavaScript and jQuery.

This entry was posted in JavaScript, jQuery and tagged , .
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

To include code in your comment: Paste your code in the comment form, select it and then click the language link button below. This will wrap your code in a <pre> tag(or shortcode) and format it when submitted.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">