Image swap with Javascript, using event onclick

Associate
Joined
17 Jan 2005
Posts
632
Location
London, UK
Ok need a javascript guru to help me out.

At the moment I have some stuff happening when a user click on an image using the event onclick.

Basically I've given an image an ID say "1". I would like someone to give me the code in which I can change the src for an image using it's ID.

Regards,
King :)
 
I believe it can simply be done with CSS and Classes.

You have a blank hyperlink, you set a background picture to it so it has a certain width and height to match the picture, which is all defined in the CSS

You then have the onclick thingy set to change class of the hyperlink to one which has a different picture.

Would this not work?
 
I'm not looking to swap the background picture of a cell or anything, as the image is the thing I will be clicking on to cause the "onclick" event.

Anyone else?

Cheers,
King
 
Try this, probably can be done a better way:-

Code:
<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
	<link rel="stylesheet" type="text/css" href="mystyle.css"/>
</head>

<script language="Javascript">
<!--

function swapimage(id, newimage)
{
	var image = document.getElementById(id);
	image.src = newimage;
}

//-->
</script>

<body>

<img src='ie.jpg' id='image'></img>

<a href=# onclick="javascript:swapimage('image', 'firefox.jpg')">Test</a>

</body>

</html>
 
PsychoDuck said:
Try this, probably can be done a better way:-

Code:
<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
	<link rel="stylesheet" type="text/css" href="mystyle.css"/>
</head>

<script language="Javascript">
<!--

function swapimage(id, newimage)
{
	var image = document.getElementById(id);
	image.src = newimage;
}

//-->
</script>

<body>

<img src='ie.jpg' id='image'></img>

<a href=# onclick="javascript:swapimage('image', 'firefox.jpg')">Test</a>

</body>

</html>

Ill give it a try :)
 
don't forget you can also apply onClick to the image itself, it doesn't need to be in an anchor:

Code:
<script language="JavaScript">
i = 1;

function RotateImage (obj)
{
    if (i > 10) {
        i = 0;
    }

    i++;
    obj.src = "images/image" + i + ".jpg";   
}

</script>

<img src="images/image1.jpg" onClick="RotateImage(this)" style="cursor:hand;" />
Though the cursor bit doesn't work in FF (or Opera afaik)
 
Only problem is that the href="#" causes the page to move to the top after the onclick event.

Is there anything else I can put in href to stop the page re-loading at the top, but still making the image as a link?

Thanks,
King :)
 
Back
Top Bottom