DavidN
DavidN

Reputation: 23

javascript rollover image - (how) can I set css styles for onmouseover image?

newbie here so pls be patient :)

I have an image (Image#1) which is aligned against the far left of the page (all body padding and margins set to 0) and have added some rollover javascript so a new image (Image#2) appears in its place on mouseover. Image#2 is larger than Image#1.

At the moment, on mouseover Image#2 appears but is not aligning far left against the page (the default page margins seem to have been re-introduced and body CSS rules ignored).

Is there anyway of applying an ID to Image#2 so I can control the CSS styles for it? Or any other way of removing the margin which appears on mouseover? Basically I would like the 2 images to overlap at the far left corner.

Help much appreciated. Thanks!

Upvotes: 1

Views: 674

Answers (4)

stanwilsonjr
stanwilsonjr

Reputation: 59

Better to use the anchor hover state in CSS to swap out a background image instead of using javascript for something so simple. Also you should make the images one image so that you can load them at one time and just change the background position on hover...

http://jsfiddle.net/k36am/

Upvotes: 0

DrStrangeLove
DrStrangeLove

Reputation: 11557

<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>

$('img#id').mouseover(function(){
$(this).css("property","value");

});

it requires jQuery..

//////////////////////////////////////////////////////////////////////////////////////

var elem = document.getElementById("id"); //your img id is passed in here
elem.onmouseover= function(){
this.style.yourPropertiesInCamelCase = "value";
}

////////////////////////////////////////////////////////////////////////////////////// P.S.: You can google camelCase if you don't know what it is... Be careful with css properties in "pure" Javascript. There are possible browser inconsistencies... Your code can become not crossbrowser...

Upvotes: 1

ndrdm
ndrdm

Reputation: 797

You might use a with fixed dimensions and 0-paddings and add the images inside it. It might work? Not sure.

Anyway, to do roll-over, you need to change the "src" attribute of the initial image. The rest should remain the same.

Upvotes: 0

Arve
Arve

Reputation: 8128

Did you concider...

<script type="text/javascript">
function changeImage() {
   document.getElementById("theImg").src = "other.gif";
}
</script>

<img src="/myImage.gif" id="theImg" onmouseover="changeImage()" />

Upvotes: 0

Related Questions