How to use Visibility property In JavaScript
This approach uses the mouseover and mouseout events to control the visibility of a popup element when hovering over a button. Initially, the popup is hidden (visibility: hidden in CSS). When the mouse hovers over the button, the mouseover event is triggered, and the popup’s visibility is set to visible using the style.visibility property in JavaScript. Similarly, when the mouse moves out of the button (mouseout event), the popup’s visibility is set back to hidden, hiding the popup again.
Example: This example uses visibility property to open a Popup on Hover using JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Popup on Hover</title>
<style>
.container {
position: relative;
/* display: inline-block; */
text-align: center;
}
.popup {
visibility: hidden;
position: absolute;
top: 50px;
left: 50%;
height: 50px;
width: 200px;
transform: translate(-50%, 0);
background-color: rgb(228, 228, 175);
color: green;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
z-index: 1;
}
.popup.show {
visibility: visible;
}
</style>
</head>
<body>
<div class="container">
<div id="hoverButton">Hover Over Content
- Javascript Visibility property</div>
<div id="popup" class="popup">
Welcome to w3wiki!
</div>
</div>
<script>
const hoverButton = document.getElementById('hoverButton');
const popup = document.getElementById('popup');
hoverButton.addEventListener('mouseover', () => {
popup.style.visibility = 'visible';
});
hoverButton.addEventListener('mouseout', () => {
popup.style.visibility = 'hidden';
});
</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