Skip to content Skip to sidebar Skip to footer

How To Get Selected Index On Mouseover?

could you please tell me how I will get selected Item index on mouseover ..I have a list , when I mouseover the list I added hover class .But I need the selected Item . here is my

Solution 1:

Use index() and move selector to the <li>

$('#main-menu li').on({
    mouseenter: function() {
      console.log("over index " + $(this).index())
    },
    mouseleave: function() {
      console.log("leave index " + $(this).index())
    }
});

Solution 2:

You could bind the mouseenter and mouseleave events to the list items. In this way, $(this) will contain the piece of information you need and with jQuery index function you can obtain its index:

$(function() {
  $('#main-menu li').on({
    mouseenter: function() {
      console.log("mouse over: " + $(this).index())
    },
    mouseleave: function() {
      console.log("mouse leave: " + $(this).index())
    }
  });
})
#main-menuulli:hover {
  background-color: red
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="main-menu"><section><ul><li><a>a</a></li><li><a>b</a></li><li><a>c</a></li></ul></section></div>

Solution 3:

Use the CSS property counter no JS, please review the demo.

Fiddle

Snippet

li {
  font: 40016px/1.5'Consolas';
  text-decoration: none;
  list-style: none;
  cursor:pointer;
  text-align: center;
  padding: 01ex;
  margin: 0002ex;
}

li:before {
  opacity: 0;
}

li:hover:before {
  content: idx;
  opacity: 1;
  background-color: black;
  color: yellow;
  padding: 01ex;
  text-align: left;
  margin: 02ex00;
}

li:hover {
  background: yellow;
  color: black;
}

ul {
  counter-reset: idx -1;
}

li:before {
  counter-increment: idx;
  content: counter(idx);
}
<divid="main-menu"><section><ul><li><a>A</a></li><li><a>B</a></li><li><a>C</a></li><li><a>D</a></li><li><a>E</a></li><li><a>F</a></li><li><a>G</a></li><li><a>H</a></li><li><a>I</a></li></ul></section></div>

Post a Comment for "How To Get Selected Index On Mouseover?"