window.onload = rolloverInit;

function rolloverInit() {
	for (var i=0; i<document.images.length; i++) {
		if (document.images[i].parentNode.tagName == "A") {
			setupRollover(document.images[i]);
		}
	}
}

function setupRollover(thisImage) {
	thisImage.outImage = new Image();
	thisImage.outImage.src = thisImage.src;
	thisImage.onmouseout = rollOut;

	thisImage.overImage = new Image();
	thisImage.overImage.src = "images/" + thisImage.id + "_on.gif";
	thisImage.onmouseover = rollOver;	
}

function rollOut() {
	this.src = this.outImage.src;
}

function rollOver() {
	this.src = this.overImage.src;
}

this is a code to make a menu on mouse out and mouse over,
so what i wonted to know is their any other better way to do this . thanx

chathuD,

Sticking with basic coding, there's no particular advantage in having a new Image() for the images already loaded automatically by the HTML. All you need for these is to store each image's src string so it can be recalled on mouseout. Meanwhile, the rollovers are not preloaded automatically so new Image() is entirely appropriate.

You could possibly reconfigure your code as follows:

window.onload = function(){
	for (var i=0; i<document.images.length; i++) {
		if (document.images[i].parentNode.tagName == "A") {
			var img = document.images[i];
			img.outsrc = img.src;
			img.overImage = new Image();
			img.overImage.src = "images/" + img.id + "_on.gif";
			img.onmouseout = rollOut;
			img.onmouseover = rollOver;
		}
	}
	function rollOut() {
		this.src = this.outsrc;
	}
	function rollOver() {
		this.src = this.overImage.src;
	}
};

The main advantage here is mainly that nothing is put into the global namespace, which is an issue when javascript becomes very complex and/or you start using other people's js libararies. Apart from that, my code is not really significantly different from yours - maybe very slightly more memory efficient but no more than that.

A way to make things simpler would be to use something like jQuery or Prototype, which would allow your code to reduce down to maybe four or five lines. However, these libs are a minimum of about 65k which is overkill if you just want to set up a few image rollovers.

Yet another aproach is to use "sprites" for the image rollovers. The sprite technique uses a single background image for both states (rollover and rollout) and shifts its origin to reveal just the required part. Sprites have the advantage of being fast and don't require a separate rollover image to be preloaded. They are well described here. There are many other examples and discussions on the web.

Airshow

wow...thanx ....very much

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.