Rob H
Rob H

Reputation: 13

Applying jQuery hover to multiple elements using jQuery each

I'm trying to get the following working so I can make certain elements of a page reveal others on hover using jQuery. I'm trying to use the data attribute of the hover element to pick the revealed element.

I just can't seem to get this working. Or is there a better way to do this?

function setUpServiceHover(){
 $( ".poster-banners__poster" ).each(function(i) {
  $(this).hover(
   function () {
    $("#service_" + ($(this).data('target')).addClass('intro__service--show'));
    $("#service_" + ($(this).data('target')).removeClass('intro__service--hidden'));
  },
   function () {
    $("#service_" + ($(this).data('target')).addClass('intro__service--hidden'));
    $("#service_" + ($(this).data('target')).removeClass('intro__service--show'));
  })
 });
}

setUpServiceHover();

Appreciate the help.

Thanks.

Upvotes: 1

Views: 65

Answers (1)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28523

you don't need to iterate for hover effect, just add hover event handler as shown below

NOTE: you need not to put this script inside setUpServiceHover() function and remove this function. You need to put it inside document.ready.. or $(function().. to ensure DOM loaded.

$(function(){
   $(".poster-banners__poster").on("hover",
       function () {
        $("#service_" + ($(this).data('target')).addClass('intro__service--show'));
        $("#service_" + ($(this).data('target')).removeClass('intro__service--hidden'));
      },
       function () {
        $("#service_" + ($(this).data('target')).addClass('intro__service--hidden'));
        $("#service_" + ($(this).data('target')).removeClass('intro__service--show'));
      });
  });

Upvotes: 1

Related Questions