Kevin Kevin - 1 month ago 12
jQuery Question

Add diferent classes to different elements with .hover()

I'm trying to add different classes to different elements when one is on hover in order to create some animations. I expect that when I hover the first element, it also adds the rest of the classes, right now it only adds hover-1 to the first element.

The link is this and the jquery code is:

$('.explorar-seccion:eq(0)').hover(
function(){ $(this).addClass('hover-1') },
function(){ $(this).removeClass('hover-1') },
function(){ $('.explorar-seccion:eq(1)').addClass('hover-2') },
function(){ $('.explorar-seccion:eq(1)').removeClass('hover-2') },
function(){ $('.explorar-seccion:eq(2)').addClass('hover-3') },
function(){ $('.explorar-seccion:eq(2)').removeClass('hover-3') },
function(){ $('.explorar-seccion:eq(3)').addClass('hover-4') },
function(){ $('.explorar-seccion:eq(3)').removeClass('hover-4') },
function(){ $('.explorar-seccion:eq(4)').addClass('hover-5') },
function(){ $('.explorar-seccion:eq(4)').removeClass('hover-5') }
);


The html is:

<a href="/que-ver.html" class="explorar-seccion">
<!-- Some Code -->
</a>
<a href="/deporte.html" class="explorar-seccion">
<!-- Some Code -->
</a>
<a href="/historia.html" class="explorar-seccion">
<!-- Some Code -->
</a>
<a href="/comida.html" class="explorar-seccion">
<!-- Some Code -->
</a>
<a href="/alojamiento.html" class="explorar-seccion">
<!-- Some Code -->
</a>


EDIT
Clarify that it doesn't work as expected.

Answer

So your issue here is that you are trying to use more than 2 arguments for the .hover()-function. The first argument is for the mousein event and the second for the mouseout event.

So your example would correctly like this:

$('.explorar-seccion:eq(0)').hover(
   function() {
     $(this).addClass('hover-1');
     $('.explorar-seccion:eq(1)').addClass('hover-2');
     $('.explorar-seccion:eq(2)').addClass('hover-3');
     $('.explorar-seccion:eq(3)').addClass('hover-4');
     $('.explorar-seccion:eq(4)').addClass('hover-5');
   },
   function() {
     $(this).removeClass('hover-1');
     $('.explorar-seccion:eq(1)').removeClass('hover-2');
     $('.explorar-seccion:eq(2)').removeClass('hover-3');
     $('.explorar-seccion:eq(3)').removeClass('hover-4');
     $('.explorar-seccion:eq(4)').removeClass('hover-5');
   }
 );

Example


When you want to apply a class for each element independently you can go with this:

 $('.explorar-seccion').hover(
   function() {
     var $this = $(this),
       eq = $this.index() + 1;
     $this.addClass('hover-' + eq);
   },
   function() {
     var $this = $(this),
       eq = $this.index() + 1;
     $this.removeClass('hover-' + eq);
   }
 );

Example

Comments