How to hover reciprocally on different elements with jquery.

61 views Asked by At

I'm trying to make it so that when you hover a list item, the corresponding piece is highlighted, and when you hover the piece, the corresponding list item is highlighted.

So far when you hover on the list item, it does highlight the corresponding map area, but how would I write it so that it hovered reciprocally?

I tried:

              $('.one, #one').hover(function(){     
                    $('#one, .one').attr("fill", "#213A46");
                    $(".info-one").fadeIn();
                },     
                function(){    
                    $('#one, .one').attr("fill", "#009A8B");   
                    $(".info-one").hide();
                });

and that did not seem to work. Any suggestions would be helpful. Here's a codepen of what I'm currently working on as well: http://codepen.io/anon/pen/zGzoMY

3

There are 3 answers

0
AudioBubble On

You can't change the state of an element, so you do have to change your .region-list li:hover { by .region-list li:hover, .region-list li.hover {.

Then you can add it in your JS, i.e. :

$('#four').hover(
    function() {     
        $('#four').attr("fill", "#213A46");
        $('.four').addClass('hover');
        $(".info-four").fadeIn();
    },     
    function() {    
        $('#four').attr("fill", "#3F6C80");
        $('.four').removeClass('hover');
        $(".info-four").hide(); 
    }
0
Leo Bauza On

This isn't possible. You will need to add a class like .hover to the element.

see: https://forum.jquery.com/topic/jquery-triggering-css-pseudo-selectors-like-hover

The way to trigger the hover on the li by hovering on the map is something like this:

$('#one').hover(function() {
  $('.one').trigger('mouseenter');
});

But to add the class you will do something like

$('#one').hover(function() {
  $('.one').addClass('hover');
});

Then remember to remove the class on mouseleave.

0
Barmar On

You need to add the hover handler to the graphic that contains #one. Otherwise, when you mouse over the text inside the polygon, that's treated as leaving the polygon.

$('.one, g:has(#one)').hover(function() {
    $('#one').attr("fill", "#213A46");
    $('.region-list .one').css({
      backgroundColor: '#213a46',
      color: '#ffffff'
    });
    $(".info-one").fadeIn();
  },
  function() {
    $('#one').attr("fill", "#009A8B");
    $('.region-list .one').css({
      backgroundColor: 'inherit',
      color: 'inherit'
    });
    $(".info-one").hide();
  });

Modified Codepen

I've only updated #one, the others are similar. It would be better to implement this using DRY methods where you find the reciprocal elements using data attributes, but I didn't bother with that rewrite.