Skip to content Skip to sidebar Skip to footer

How To Change The Div Background Image In Mouse Over

Possible Duplicate: Is there any way to hover over one element and effect a different element? How to change the div background image,in mouse over the another div,using css .

Solution 1:

With the markup you supplied, this is indeed possible with CSS alone:

<a><imgsrc="http://placehold.it/100x100" /><div></div></a>

You can use the :hover pseudo selector to select the div when the anchor has been hovered

a:hoverdiv
{
    background-image: url(http://placehold.it/400x400);
}

This will change the div's background when the anchor is hovered. This doesn't work in all cases, you must be aware of the relationship of the elements and use the appropriate selector. If the elements have no relationship, you will have to use Javascript (or one of its libraries.)

http://jsfiddle.net/Kyle_Sevenoaks/fPGU3/

Solution 2:

This will achieve what you're looking for though there are better ways to do this, using sprites and background-position for example. However:

Your HTML

<aclass="selector">My Link</a>

Your CSS

.selector {
    background-image:url(myImage.jpg);
}

.selector:hover {
    background-image:url(myHoverImage.jpg);
}

Jquery solution

HTML

<aclass="selector"data-type="bgChanger1">
    My Link
</a><divdata-type="bgChanger1">
    ...
</div>

JQUERY

$(document).ready(function()
{
    var hoverElement = $('.selector'),

        dataType = hoverElement.attr('data-type'),

        linkedDiv  = $('div[data-type="' + data-type + '"]');

    hoverElement.hover(function(e)
    {
        e.preventDefault()

        linkedDiv.css('background-image', 'hoverImage.jps');
    },
    {
        linkedDiv.css('background-image', 'normalImage.jpg');
    });
});

Solution 3:

You can use jquery to do this.

Your markup:

<div id="div1"></div>
<div id="div2"></div>

Your script:

$("#div1").mouseover( function() {
   $("#div2").css("background-image", "url('image.png')");
});

Solution 4:

just add a jquery script as follows:

 $(document).ready(function() {
    $('#div1').hover(function(){
      $('#div2').css("background","url(image_url)");
    });
 });       

Post a Comment for "How To Change The Div Background Image In Mouse Over"