Reputation: 1084
Here is my goal:
I am looking for a JavaScript and CSS solution. If you can help but you can only post a JQuery solution I will still appreciate it but I will have to translate it to straight JavaScript.
So far I have tried:
Thank you for your help with this!
Here is a JSFiddle that is a starting point for a solution https://jsfiddle.net/ypn5f1ng/
HTML
<div id=content>
content
<div class=item>item 1</div>
<div class=item>item 2</div>
more content
</div>
CSS
body { background:green; }
#content { z-index:100; width:500px; position:absolute; left:0px; right:0px; margin-left:auto; margin-right:auto; background:white; margin-top:10px; background:lightblue; padding:5px; }
div.item { background:pink; margin:5px}
div.hover { background:yellow; height:15px; width:100px; z-index:101; position:fixed }
JavaScript
function getElem(event) {
if (!event) {
event = window.event;
}
var elem = null;
if (event.target) {
elem = event.target;
} else if (event.srcElement) {
elem = event.srcElement;
}
if (elem && elem.nodeType == 3) {
elem = elem.parentNode;
}
return elem;
}
var hoverDiv = null;
function onItemMouseOver(event) {
var elem = getElem(event);
if (!hoverDiv) {
hoverDiv = document.createElement('DIV');
hoverDiv.className = "hover";
document.body.appendChild(hoverDiv);
//elem.appendChild(hoverDiv);
hoverDiv.style.right=100;
hoverDiv.style.top=-100;
}
}
function onItemMouseOut(event) {
if(hoverDiv) {
hoverDiv.parentNode.removeChild(hoverDiv);
hoverDiv = null;
}
}
var items = document.getElementsByClassName("item");
for(var i = 0; i < items.length; ++i) {
var item = items[i];
item.onmouseover = onItemMouseOver;
item.onmouseout = onItemMouseOut;
}
Upvotes: 0
Views: 43
Reputation:
<div class='a'>
<div class="b">
<a href="a">asfdwa</a>
</div>
</div>
.a {
position: relative;
width: 300px;
height: 300px;
background: lightgray;
}
.b {
position: absolute;
top: 0;
left: 0;
width: 300px;
height: 80px;
background: pink;
opacity: 0;
transition: .2s opacity ease-in-out;
}
.b a {
display: block;
margin: 1rem;
}
.a:hover .b {
opacity: 1;
}
Upvotes: 1
Reputation: 408
The best approach is to use CSS only if possible (no JS).
In this situation, I would recommend to put the div you would like to display on hover into the div that is the trigger.
<div class="parent">
<div class="child">
...
</div>
...
</div>
Than the CSS would look like this:
div.child {
display: none;
}
div.parent:hover div.child {
display: block;
}
With this technique you can position the child even to get outside the parent and it will not disappear if you get out of the parent if you are still on the child since the child is technically (not visually) in the parent. You just need to make sure that the parent at least touches the displayed child since the child will disappear if you travel over the gap between them with your cursor (the cursor won't be on the parent nor on the child)
Upvotes: 0