Mouseover/out only on one menu item within several caught by jQuery selector

Asked

Viewed 24 times

-1

When I hover over a menu item everyone gets the mouseover/out effect. I wonder if which procedure/function to use when hovering the mouse in the menu apply the effect only on this menu item.

<div id="grid-container">

    <div class="grid-item"></div>

    <div class="grid-item"></div>

    <div class="grid-item"></div>

    <div class="grid-item"></div>

</div>

<script>

    var grid_item = $('.grid-item').ea;

    $(document).ready(() => {

        // Adicionando o evento com mouseover.
        grid_item.mouseover( () => {
            grid_item.addClass('item-hover');
        });

        // Removendo o evento com mouseout.
        grid_item.mouseout( () => {
            grid_item.removeClass('item-hover');
        });

    });

</script>

1 answer

0


jQuery has its own method of calling two events at the same time, the .Hover:

$(elemento).hover(
   function(){
      // função do mouseenter (quando passa o mouse)
   },
   function(){
      // função do mouseleave (quando retira o mouse)
   }
);

Example adding the class:

$(".grid-item").hover(
   function(){
      $(this).addClass("item-hover");
   },
   function(){
      $(this).removeClass("item-hover");
   }
);
.item-hover{
   color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="grid-container">

    <div class="grid-item">item 1</div>

    <div class="grid-item">item 2</div>

    <div class="grid-item">item 3</div>

    <div class="grid-item">item 4</div>

</div>

  • Thank you very much friend! Your code helped me to find the problem of why I was selecting everything. I believe I was holding the grid-item class in a variable, and that didn’t work. From the moment I started to take the direct element of the $('grid-item') code and use $(this) started to select only one. I don’t quite understand why, if you know how to inform me, I would be grateful. In addition to knowing the exact time to store in item/ns variables by selector or use direct.

  • The $(this) represents the element that called the event.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.