Reputation: 1029
I am trying to have an image show up when the user hovers over some text in a span. I have gotten it to work for the user hovering over an entire div, but I just want it to trigger over the span. Here's the full code:
<html>
<head>
<title>gif test</title>
<style>
#gif {
position: absolute;
left: 50px;
top: 120px;
display: none;
}
#trigger:hover #gif {
display: block;
}
</style>
</head>
<body style="font-family:Helvetica;">
<h1>gif test</h1>
<hr noshade />
<p>Hover <span id="trigger">here</span></p>
<div id="gif"><img src="img/hey.gif" /></div>
</body>
</html>
I wanted it to be so that when the user puts their mouse over "here", the image shows, but not if the mouse is over "Hover". Is there something special about spans that prevents hovers from working the same way? Or am I referencing the #gif div incorrectly?
Thanks.
Upvotes: 1
Views: 3724
Reputation: 22402
Your CSS is incorrect, #trigger;hover #gif means a child of #trigger:hover with the id gif. Meaning your DOM is supposed to be:
<div id='trigger'>
<div id='gif'><img src='img/hey.gif' /></div>
</div>
If you want to control the state of an element outside the hierarchy, where the controlled element is not a child or a sibling, then CSS isn't enough you need some javascript:
<html>
<head>
<title>gif test</title>
<style>
#gif {
position: absolute;
left: 50px;
top: 120px;
display: none;
}
#gif.show {
display: block;
}
</style>
</head>
<body style="font-family:Helvetica;">
<h1>gif test</h1>
<hr noshade />
<p>Hover <span id="trigger" onmouseover="show()" onmouseout="hide()">here</span></p>
<div id="gif"><img src="img/hey.gif" /></div>
</body>
<script type="text/javascript">
showBox() {
var gifbox = document.getElementById("gif");
gifbox.classList.add("show");
}
hideBox() {
var gifbox = document.getElementById("gif");
gifbox.classList.remove("show");
}
</script>
</html>
Upvotes: 2
Reputation: 1029
Per j08691, I had my hierarchies wrong. New code:
<html>
<head>
<title>gif test</title>
<style>
#gif {
position: absolute;
left: 50px;
top: 120px;
display: none;
}
#trigger:hover + #gif {
display: block;
}
</style>
</head>
<body style="font-family:Helvetica;">
<h1>gif test</h1>
<hr noshade />
<p>Hover <span id="trigger">here</span>
<span id="gif"><img src="img/hey.gif" /></span>
</p>
</body>
</html>
Now, the image is a sibling of #trigger (both have parent <p>
; the +
is the sibling selector).
Upvotes: 1