Mouseover Element using JavaScript

Creating a mouseover event using JavaScript involves adding an event listener to an HTML element and defining the code to execute when the mouse pointer enters the element. Here's an example of how you can implement a mouseover event:


1. Set up your HTML structure:

<!DOCTYPE html>
<html>
<head>
  <title>Mouseover Example</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div id="targetElement">Hover over me!</div>

  <script src="script.js"></script>
</body>
</html>

2. Create a CSS file (styles.css) to style the target element:

css
#targetElement {
  width: 200px;
  height: 200px;
  background-color: lightblue;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  cursor: pointer;
}

3. Now, create a JavaScript file (script.js) to handle the mouseover event:

javascript
document.addEventListener('DOMContentLoaded', function () {
  const targetElement = document.getElementById('targetElement');

  function handleMouseOver() {
    targetElement.textContent = 'Mouse is over!';
    targetElement.style.backgroundColor = 'lightgreen';
  }

  function handleMouseOut() {
    targetElement.textContent = 'Hover over me!';
    targetElement.style.backgroundColor = 'lightblue';
  }

  targetElement.addEventListener('mouseover', handleMouseOver);
  targetElement.addEventListener('mouseout', handleMouseOut);
});

4. Place all the files (HTML, CSS, and JS) in the same folder.


Open the HTML file in a web browser, and you should see a div element with the text "Hover over me!" When you move the mouse pointer over the element, the text and background color will change. When you move the mouse pointer out of the element, it will revert to its initial state.

Adjust the CSS classes and styles as per your design requirements. You can customize the event handlers (`handleMouseOver` and `handleMouseOut`) to perform different actions based on your needs, such as showing/hiding additional content, animating elements, or triggering other functionality.


Output:

img


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext