How to use display property In JavaScript
- This approach will use event listeners and display property in javascript.
- mouseenter or mouseover event listener will be used whenever cursor hovers over the HTML Element
- mouseleave or mouseout will be used whenever cursor leaves the HTML Element
- use document.getElementById() method to target specific HTML Element.
- display property will be used to show or hide the pop up
Example: This example shows the use of display property for showing the popup on hover.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Hover Popup Using Javascript
Event Listener</title>
<style>
#elementToHover {
display: inline-block;
position: relative;
}
#elementToPopup {
display: none;
position: absolute;
top: 30px;
left: 7px;
background-color: #555;
color: #fff;
padding: 8px;
border-radius: 5px;
}
</style>
</head>
<body>
<div id="elementToHover">Hover Over Content
- Javascript Approach</div>
<div id="elementToPopup">Popped Up Content
- Javascript Approach</div>
<script>
const elementToHover = document.
getElementById('elementToHover');
const elementToPopup = document.
getElementById('elementToPopup');
elementToHover.addEventListener('mouseenter',
() => {
elementToPopup.style.display = 'block';
});
elementToHover.addEventListener('mouseleave',
() => {
elementToPopup.style.display = 'none';
});
</script>
</body>
</html>
Output:
How to Open a Popup on Hover using JavaScript ?
We will be learning about the ways to open a pop-up when the cursor hovers over the HTML Element. Hover is a useful UI interaction that helps in getting more information about a specific HTML element.
Pop Up can be shown as the additional data to make things much more understandable. It responds to and gets triggered by the common user interface interactions. In JavaScript, pop-ups can be made visible by using event listeners.
These are the following approaches:
Table of Content
- Using display property
- Using ClassList property
- Using Visibility property