Log in

View Full Version : how to put effect onmouseover changing background?



davelf
06-06-2011, 09:53 AM
I have this script to change background image onmouseover:



<html>
<head>
<style type="text/css">
#test {
background-image:url(images/background-2.jpg);
height:1300px;
width:1800px;
}
</style>
<script type="text/javascript">
function changeBgImage (image, id) {
var element = document.getElementById(id);
element.style.backgroundImage = "url("+image+")";
}
</script>
</head>
<body>
<div
id="test"
onMouseOver="changeBgImage('images/background-2.jpg', 'test')"
onMouseOut="changeBgImage('images/background-3.jpg', 'test')">
</div>
</div>
</body>
</html>


How to add some effect like fade for example. I know we can use jquery, the problem is i'm not really understand how to make it work. Example or tutorial should be nice. Thanks a lot:)

Beverleyh
06-06-2011, 12:23 PM
this should start you off


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Div Swop</title>

<style type="text/css">
#swop1, #swop2 { position:absolute; top:50px; left:50px; width:150px; height:150px; }
#swop1 { background:url('images/1.jpg'); }
#swop2 { background:url('images/2.jpg'); display:none; }
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#swop1').mouseover(function(){ $('#swop2').fadeIn(500)});
$('#swop2').mouseout(function(){ $('#swop2').fadeOut(500)});
});
</script>

</head>
<body>

<div id="swop1"></div>
<div id="swop2"></div>

</body>
</html>

davelf
06-06-2011, 02:16 PM
hmm, thx beverleyh for your reply.
I have already tried to use the script you gave to me, but nothing happen? is there something you forgot?

Thank you very much...

Beverleyh
06-06-2011, 03:14 PM
I don't think so - it works on my local machine using my own images as referenced (only quickly tested in IE8, Firefox, Safari and Chrome and all those browsers are working).

Have you definitely replaced the CSS background URL images with your own and checked the paths are correct?

Maybe change the URLs to absolute and surround with "images/1.jpg" instead of 'images/1.jpg' too

traq
06-06-2011, 07:38 PM
some servers also have problems with filenames that start with numbers - not common, but it happens