Chris James Champeau
Chris James Champeau

Reputation: 994

Change page background when rollover an image using javascript

I am currently using javascript for this but if you have a better solution I am all ears. So I have my wrapper and its background and within that is all my content including a button that I want to when hovering fade to change the background of the wrapper/page.

my css looks like this

#wrapper {position: absolute; min-width:550px; width:100%; height:100%; background: url(img/bg.jpg) no-repeat center top;}

and then my html

<div id="wrapper">
<div id="content">
<div class="logo">
<img src="img/logo1.png" />
</div>
<div class="button">
<img src="img/dj.png" onMouseOver="changeBgImage('img/bg2.jpg','wrapper')" onMouseOver="changeBgImage('img/bg2.jpg','wrapper')"/>
</div>
</div>
</div>

and then my javascript

<script type="text/javascript">
    function changeBgImage (image, id) {
var element = document.getElementById(id);
element.style.backgroundImage = "url("+image+")";
    }
</script>

So as it sits it works, it changes the background and then changes it back on mouseout, however I want it to fade in and out. How would I go about doing this??

EDIT: attempted both solutions below, neither seem to work or apply

Upvotes: 1

Views: 775

Answers (2)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

Here is a nice, clean way to do it.

http://jsfiddle.net/Diodeus/gYyBL/

<img src="http://i.imgur.com/vdDQgb.jpg" hoverImg="http://i.imgur.com/Epl4db.jpg">

$('body').find('*[hoverImg]').each(function(index){
    $this = $(this)
    $this.wrap('<div>')     
    $this.parent().css('width',$this.width())  
    $this.parent().css('height',$this.width())
    $this.parent().css('background-image',"url(" + $this.attr('hoverImg')+")")
        $this.hover(function() {
            $(this).stop()
            $(this).fadeTo('',.01)    
        },function() {
            $(this).stop()
            $(this).fadeTo('',1)             
        })                    
});

Upvotes: 2

Hanlet Esca&#241;o
Hanlet Esca&#241;o

Reputation: 17370

I like your solution. Check this out for an option for the fading effect you are trying to accomplish.

Good luck!

Edit: https://stackoverflow.com/a/1055432/752527 also seems like a nice clean solution.

Upvotes: 0

Related Questions