Reputation: 177
<html>
<head>
<script>
function show_function() {
var example_image=document.getElementById("example_image");
example_image.src="example_one.png";
}
function hide_function() {
var example_image=document.getElementById("example_image");
example_image.src="example.png";
}
</script>
</head>
<body>
<div class="one" onmouseover="show_function()" onmouseout="hide_function()">
<img id="example_image" src="example.png">
</div>
<div class="two" onmouseover="show_function()" onmouseout="hide_function()">
<img id="example_image" src="example.png">
</div>
</body>
</html>
When I hover the mouse over first div,the image changes. But when I hover the mouse over second div then also the image from the first div changes.
Does anyone know how to do it only in javascript?
Upvotes: 0
Views: 4276
Reputation: 4985
I think you want the first child node [0] of the div. and pass the hovered object into the callback.
function show(e){
document.getElementById('label').innerHTML = e.children[0].id;
e.style.border = "solid 2px red";
}
function hide(e){
e.style.border = "0";
}
<div class="one" onmouseover="show(this)" onmouseout="hide(this)">
<img id="example_image" src="example.png" class="one" >
</div>
<div class="two" onmouseover="show(this)" onmouseout="hide(this)">
<img id="example_image" src="example.png" class="two">
</div>
<p id='label' ></p>
Upvotes: 0
Reputation: 6476
You can do it like this:
show_function = function (container) {
container.childNodes[1].src = "example_one.png";
}
hide_function = function (container) {
container.childNodes[1].src = "example.png";
}
then in HTML, pass this
to function:
<div class="one" onmouseover="show_function(this)" onmouseout="hide_function(this)">
<img id="example_image" src="example.png">
</div>
<div class="two" onmouseover="show_function(this)" onmouseout="hide_function(this)">
<img id="example_image" src="example.png">
</div>
Upvotes: 0
Reputation: 9692
Like Danko said, ID must be unique. Next step will be to insert variables into your function:
<html>
<head>
<script>
function show_function(id, hide)
{
var example_image=document.getElementById(id);
if(hide){
example_image.src="example.png";
} else{
example_image.src="example_one.png";
}
}
</script>
</head>
<body>
<div class="one"
onmouseover="show_function('example_image1')"
onmouseout="show_function('example_image1', true)" />
<img id="example_image1" src="example.png">
</div>
<div class="one"
onmouseover="show_function('example_image2')"
onmouseout="show_function('example_image2', true)" />
<img id="example_image2" src="example.png">
</div>
</body>
</html>
Or you can go like this too:
<img src="example.png"
onmouseover="this.src='example_one.png';"
onmouseout="this.src='example.png';" />
Hope it helps!
Upvotes: 1