Checking code change background image with over link with jquery

129 views Asked by At

I have this code. The idea is that when the mouse is on hover the link the background-image of a div changes and when is not, shows the original image. I´ll do it with 5 links but at the moment I can´t make it works even whit one.

SCRIPT JQUERY

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {

    $("#changebg").hover(
    function() {
        //mouse over
        $('.thediv').css('background-image', 'url("www.site.com/img/img2.png")');
    }, function() {
        //mouse out
        $('.thediv').css('background-image', 'url("www.site.com/img/img1.png")');
    });
});
</script>

CSS STYLE

.thediv { position: relative; background-image:url('www.site.com/img/img1.png'); }

HTML CODE

<div class="thediv">

<div style="position: absolute;">
<a href="#" class="linkstyle" id="changebg">CHANGE</a>
</div>



</div>

And an extra... To make the same but with 5 link... EX:

<a href="#" class="linkstyle" id="changebg">CHANGE</a>
<a href="#" class="linkstyle" id="changebg1">CHANGE</a>
<a href="#" class="linkstyle" id="changebg2">CHANGE</a>

...

I have to copy and paste the same code or is there a better form to do it?

Thanks a lot :D

Have a great start of week.

2

There are 2 answers

0
HelloWorld On BEST ANSWER

You need to set a height and width on .theDiv like so:

.thediv { 
    position: relative; background-image:url('http://fpoimg.com/300x250'); 
    width:500px;
    height:500px;
}

here is a working example. Also your example images didn't work (they dont actually exist as far as I can tell) so I changed them to some filler images so you could see that my example works

1
guest271314 On

Try utilizing :hover

.thediv {
  height: 50px;
  width: 50px;
  position: relative;
  background-image: url('http://lorempixel.com/50/50/cats');
  top: 0px;
}
a[id^="changebg"]:hover {
  color: transparent;
  position: absolute;
  height: 50px;
  width: 50px;
  background-image: url('http://lorempixel.com/50/50/technics');
  z-Index: 1;
  top: 0px;
  transition: top 1ms linear;
}
<div class="thediv">
  <div style="position: absolute;">
    <a href="#" class="linkstyle" id="changebg">CHANGE</a>
    <a href="#" class="linkstyle" id="changebg1">CHANGE</a>
    <a href="#" class="linkstyle" id="changebg2">CHANGE</a>
  </div>
</div>