...

View Full Version : alternate change img src



BubikolRamios
12-17-2006, 10:25 AM
Suppose I have <IMG src = "A.jpg">
And want to change src alternately on click: A.jpg or B.jpg.

could do this like that:



var identifer;

function imgOnClick()

{
if identifer = "A.jpg"
{
document.getelementbyid("idOfImgElement").src = "B.jpg":
identifer = "B.jpg";
{
elseif identifer = "B.jpg"
{
document.getelementbyid("idOfImgElement").src = "A.jpg":
identifer = "A.jpg";
{

}

any sugestions for more clear code(I dont like having "var identifer;") or perhaps even css ?

whizard
12-17-2006, 01:06 PM
CSS can't do onClick, but it can do

:hover (essentially the same as onMouseOver)

div
{
background-image:a.jpg;
}

div:hover
{
background-image:b.jpg;
}

I don't think IE supports the :hover psuedoclass for anything except links, though

Dan

Mr J
12-17-2006, 01:45 PM
Here's one possibility


function imgOnClick(){

imgEl=document.getElementById("idOfImgElement")

if(imgEl.src.indexOf("A.jpg")!= -1){
imgEl.src = "B.jpg"
}
else{
imgEl.src = "A.jpg"
}

}

Bill Posters
12-17-2006, 01:49 PM
As you're doing a straight toggle, you don't need to store the other img filename.


function imgOnClick() {

var imgEl = document.getElementById('idOfImgElement');
imgEl.src = (imgEl.src.indexOf('A.jpg') != -1) ? 'B.jpg' : 'A.jpg';

}


…

div
{
background-image:a.jpg;
}

div:hover
{
background-image:b.jpg;
}

*ahem*

That would be…

…
background-image: url(b.jpg);
…


I don't think IE supports the :hover psuedoclass for anything except links, though
That's IE6 and below. IE7 now supports it for all elements.

whizard
12-17-2006, 02:24 PM
*ahem*


Yeah, sorry, I should have included it... I was thinking that it would be understood, not sure why lol

Dan



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum