How to use ClassList Property In JavaScript
Similar to display property, classlist approach will also use same event listeners. In this approach add() and remove() methods will be used to dynamically add classes to HTML element to show or hide the pop up.
Example: This example shows the use of add() and remove() method for showing 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;
}
#elementToPopup.show {
display: block;
}
</style>
</head>
<body>
<div id="elementToHover">Hover Over Content
- Javascript ClassList Approach</div>
<div id="elementToPopup">Popped Up Content
- Javascript ClassList Approach</div>
</body>
<script>
const elementToHover = document.
getElementById('elementToHover');
const elementToPopup = document.
getElementById('elementToPopup');
elementToHover.addEventListener('mouseover',
() => {
elementToPopup.classList.add('show');
});
elementToHover.addEventListener('mouseout',
() => {
elementToPopup.classList.remove('show');
});
</script>
</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