How to create a random number in JavaScript?

JavaScript provides a Math.random() function to producing random numbers between 0 and 1.

var n = Math.random();
 
console.log( n );

Prints something like:

0.7227701654893868

What mouse events are available in JavaScript?

The following mouse events are available:

  • mousedown
  • mouseup
  • click
  • dblclick
  • mousemove
  • mouseover
  • mouseout

Microsoft provides some proprietary events:

  • mouseenter
  • mouseleave

For a simple example, suppose we have the following div.

<div id="hello">
	HELLO
</div>

And we attach the following mouse events:

var o = document.getElementById("hello");
 
o.onmousedown = function(){ console.log("Mouse Down"); };
o.onmouseup = function(){ console.log("Mouse Up"); };
o.onclick = function(){ console.log("Click"); };
o.ondblclick = function(){ console.log("Double Click"); };
 
o.onmousemove = function(){ console.log("Mouse Move"); };
o.onmouseover = function(){ console.log("Mouse Over"); };
o.onmouseout = function(){ console.log("Mouse Out"); };

Then moving the mouse over the div and double clicking produces an output similar to:

Mouse Over
Mouse Move
Mouse Move
Mouse Move
Mouse Move
Mouse Move
Mouse Down
Mouse Up
Click
Mouse Down
Mouse Up
Click
Double Click
Mouse Move
Mouse Move
Mouse Out

More details over at Quirksmode

How to concatenate all arguments to a function in JavaScript?

Array’s have a join() method used for joining arrays that contain strings, but this can’t be used with function arguments, which are array-like, but are not actual arrays. Instead we can defer to the Array prototypes join function:

 
function concatenate() {
	return Array.prototype.join.call(arguments,"");
}
 
var s = concatenate("a","b","c");
(s === "abc"); // true

How to read a Flickr feed using jQuery?

Flicker provides image feeds in several formats, including JSON. Suppose we have the following html:

<div id="images" />

The we can append images to the div from Flickr using:

$(function(){
 
	var url = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
 
	var data = {
		format:"json",
		tags:"puppy"
	}
 
	var callback = function(data) {
		var i = data.items.length;
		while(i--) {
			var item = data.items[i];
			var title = item.title;
			var thumb = item.media.m;
 
			$("<img>")
				.attr("src",thumb)
				.appendTo("#images");
		}
	}
 
	$.getJSON(url,data,callback);
 
});

We append jsoncallback=? to the URL to handle same origin policy restrictions.

The data object allows us to specify the format as json, provide a comma separated list of tags to search for with the images – in our case, ‘puppy’.

You can read more about the Flickr public feed parameters or read more about Flickr feed services.

How to create a switch statement in JavaScript?

var num = 1,  
	str = "";
 
switch (num) {  
case 0:  
   str = "zero";  
   break;  
case 1:  
   str = "one";
   break;  
default:  
   str = "";
}  
 
(str === "one"); // true

Case statements can also be combined together.

for (var i=0; i<5; i++) {
 
	switch(i) {
	case 0:
	case 1:
		console.log("zero one");
		break;
	case 3:
	case 4:
		console.log("three four");
		break;
	default:
		console.log("default");
	}
 
}

Which outputs

zero one
zero one
default
three four
three four

How to find the integer part of a number in JavaScript?

Our first option is to use the Math.floor() for positive numbers and Math.ceil() for negative numbers.

var n, i;
 
n = 5.4321;
i = Math.floor(n);
console.log( i === 5); // true
 
n = -5.4321;
i = Math.ceil(n);
console.log( i === -5); // true

Some alternatives that may be faster include using a double bitwise not operator: ~~

var n, i;
 
n = 5.4321;
i = ~~n;
console.log( i === 5); // true
 
n = -5.4321;
i = ~~n;
console.log( i === -5); // true

( For more on this see Double bitwise NOT (~~) )

Another option is to use a bitwise or with zero.

var n, i;
 
n = 5.4321;
i = 0|n;
console.log( i === 5); // true
 
n = -5.4321;
i = 0|n;
console.log( i === -5); // true

Lastly, we can also use a bitwise left shift of zero.

var n, i;
 
n = 5.4321;
i = n << 0;
console.log( i === 5); // true
 
n = -5.4321;
i = n << 0;
console.log( i === -5); // true

How to find the position of an element relative to the page in jQuery?

The offset() method provides the position of an element relative to the whole document.

var positionRelativeToPage = $("#foo").offset();
var x = positionRelativeToPage.left;
var y = positionRelativeToPage.top;

How to find the position of an element relative to the page in JavaScript?

The position of an element relative to the whole document is found as follows:

function positionRelativeToPage(elem) {
	var x = y = 0;
	while (elem) {
		x += elem.offsetLeft;
		y += elem.offsetTop;
		elem = elem.offsetParent;
	}
	return {x:x,y:y};
}

How to find the width and height of an image using JavaScript?

Images have width and height properties.

For example, for an image already on a page:

var img = document.getElementById("puppy");
var width = img.width;
var height = img.height;

If you dynamically load an image:

var img = document.createElement("img");
img.setAttribute("src","images/puppy.jpg");
img.onload = function(e) {
	var width = img.width;
	var height = img.height;
}

How to dynamically load an image using jQuery?

In this example let’s load an image and place it into a div container within the page.

<div id="imageContainer"></div>

To load the image we create an image element, set it’s src attribute, wait for it to load, then append it to the div.

var img = $("<img/>")
	.load(function(e) {
		$("#imageContainer").append(e.target);
	})
	.attr("src","images/puppy.jpg");

Note that e.target contains a reference to the image that was just loaded.