Reputation: 41
So I have this div class:
<div id="object1">
<div class="title" onmouseover="hoverImage(event)">SPT 3</div>
</div>
And outside of that div, I have another div with a image:
<div class="hover_img" id="hover_img">
<img src="img/sptgoal.PNG">
</div>
CSS code to center the image:
.hover_img {
position:relative;
height: 100%;
width:100%;
z-index: 99;
}
.hover_img img {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display:none;
}
I only want the image to be visible when hovering the div. This is the Javascript code I have:
function hoverImage() {
var x = document.getElementById("hover_img");
x.style.display = "block";
}
But when hovering the mouse over, nothing shows up. What am I doing wrong here?
Upvotes: 0
Views: 2770
Reputation: 3765
With document.getElementById("hover_img")
you don't show the image, but the container around it (hover_img
). But you have hidden the image (.hover_img img
) in your CSS.
Use document.querySelectorAll("#hover_img>img")
for selecting your image. querySelectorAll will return a NodeList, so you have to use x[0]
for selecting the first element in list.
function hoverImage(event) {
var x = document.querySelectorAll("#hover_img>img");
var sDisplay = (event.type === "mouseout") ? "none" : "block";
x[0].style.display = sDisplay;
}
.hover_img {
position:relative;
height: 100%;
width:100%;
z-index: 99;
}
.hover_img img {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display:none;
}
<div id="object1">
<div class="title" onmouseover="hoverImage(event)" onmouseout="hoverImage(event)">SPT 3</div>
</div>
<div class="hover_img" id="hover_img">
<img src="https://picsum.photos/200/300">
</div>
Upvotes: 2
Reputation: 33
you must select another id for img:
<div class="hover_img" id="hover_img">
<img src="img/sptgoal.PNG" id="image1">
</div>
and use this id in your java script:
function hoverImage() {
var x = document.getElementById("image1");
x.style.display = "block";
}
Upvotes: 0
Reputation: 44
problem is on element selector you need to select image element for change display property not div tag.
i hope it's help full
Blockquote
function hoverImage() {
var x = document.getElementById("hover_img");
x.children[0].style.display = "block";
}
.hover_img {
position:relative;
height: 100%;
width:100%;
z-index: 99;
}
.hover_img img {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display:none;
}
<div id="object1">
<div class="title" onmouseover="hoverImage(event)">SPT 3</div>
</div>
<div class="hover_img" id="hover_img">
<img src="img/sptgoal.PNG">
</div>
Upvotes: 1