Open In App

How to Get Selected Index on Mouseover in JavaScript ?

Last Updated : 10 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To obtain the selected index on mouseover in JavaScript, attach event listeners to the parent container and utilize iteration through child elements to discover the index of the hovered element. By tracking the index of the hovered element during this process, you can determine the selected index accurately based on the mouseover event.

Approach

  • First, create a structure of the web page by using HTML elements, a parent <div> element with the id "parent" and several child <div> elements representing items.
  • JavaScript code attaches event listeners to each child <div> element inside the parent container.
  • When a mouseover event occurs on a child <div>, the code retrieves the index of that particular element within its parent container.
  • The code uses the parent container and its child elements to find out the position of the element the mouse is hovering over. It does this by looking at each child element one by one.
  • Once the position (index) of the hovered element is found, and result is displayed in the console.

Example: The example below shows how to get a selected index on mouseover in JavaScript.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width,
                   initial-scale=1.0">
    <title>Iterating through Child Elements</title>
    <style>
        #parent {
            border: 1px solid black;
            padding: 10px;
        }

        div {
            padding: 5px;
            margin: 5px;
            border: 1px solid gray;
        }
    </style>
</head>

<body>
    <div id="parent">
        <div>Item 1</div>
        <div>Item 2</div>
        <div>Item 3</div>
    </div>

    <script>
        let parentElement = document.getElementById('parent');
        let childElements = parentElement.children;

        for (let i = 0; i < childElements.length; i++) {
            childElements[i]
              .addEventListener('mouseover', function () {
                let selectedIndex = Array.from(this.parentNode.children)
                                         .indexOf(this);
                console.log(selectedIndex);
            });
        }
    </script>
</body>

</html>

Output:

imageMouseover
Output

Next Article
Article Tags :

Similar Reads