Your code is functioning correctly, but it is important to ensure that you have a valid reference to imgContainer
and a valid path to an image for the dynamically created element:
var imgContainer = document.getElementById("container");
var imgHover = document.createElement('img');
imgHover.setAttribute("src", "https://www.wpclipart.com/signs_symbol/arrows/button_arrows/play_buttons/play_button_gray.png");
imgHover.style.width = "30px";
imgHover.style.height = "23px";
imgHover.style.position = "absolute";
imgHover.style.margin = "0 auto";
imgHover.style.left = "45px";
imgHover.style.bottom = "35px";
imgHover.style.visibility = "hidden";
imgContainer.appendChild(imgHover);
imgContainer.addEventListener("mouseover", makeVisible, false);
function makeVisible(){
imgHover.style.visibility = "visible";
}
<div id="container">Hover Over Me</div>
It is recommended to avoid inline styles on elements as they can be difficult to override and lead to code duplication. Using CSS classes and the element.classList
API simplifies styling.
The use of the visibility
property affects whether an element is seen or not, but it still occupies space in the UI. In most cases, utilizing display:none
to hide elements and then removing this instruction to show them is preferred.
Furthermore, instead of using setAttribute()
, directly configuring element properties simplifies the code. Most HTML attributes correspond to JavaScript object properties, making manipulation easier.
Here is a consolidated example incorporating these suggestions:
var imgContainer = document.getElementById("container");
var imgHover = document.createElement('img');
// Set element properties directly:
imgHover.src ="https://www.wpclipart.com/signs_symbol/arrows/button_arrows/play_buttons/play_button_gray.png";
// Add pre-made classes to style the element
imgHover.classList.add("hoverImg");
imgHover.classList.add("hidden");
imgContainer.appendChild(imgHover);
imgContainer.addEventListener("mouseover", makeVisible);
function makeVisible(){
imgHover.classList.remove("hidden");;
}
.hidden { display:none; } /* Used when an element needs to be hidden */
/* Applied via JS */
.hoverImg {
width:30px;
height:23px;
position: absolute;
margin:0 auto;
left:45px;
bottom:35px;
}
<div id="container">Hover Over Me</div>