Search code examples
jqueryclassdictionaryhoverarea

jQuery affect elements with same class as clicked or hovered elements


I'm working on an application that's like a map of parts componing a game, and when i hover an area with a certain class, i need an image with the same class as the area to fade in.

This is what i got working:

$(document).ready(function() {
    $("area.THECLASS").hover(function() {
         $("img.THECLASS").fadeIn(200);
    }, function() {
         $("img.THECLASS:not(.stay)").fadeOut(200);
    );
});

I'm going to have a lot of parts and classes and i need to make it work so that it can recognize an img with the same class as the hovered area and fade it in.

Is there any way to do that?


Solution

  • You can retrieve the classes assigned to an element using the className property, however, as an element can have multiple classes, there's a chance of ambiguity stopping you knowing which class to use.

    However, if you can guarantee only one class will be present, give the following a shot;

    $('area').hover(function () {
        var theClass = $(this).prop('className');
    
        $('img.' + theClass).fadeIn(200);
    }, function () {
        var theClass = $(this).prop('className');
    
        $('img.' + theClass + ':not(.stay)').fadeOut(200);
    });
    

    If multiple classes exist, you might want to consider using a data-* HTML attribute;

    <area data-target="THECLASS" />
    

    and then in your code;

    $('area').hover(function () {
        var theClass = $(this).data('target');
    
        $('img.' + theClass).fadeIn(200);
    }, function () {
        var theClass = $(this).data('target');
    
        $('img.' + theClass + ':not(.stay)').fadeOut(200);
    });
    

    For more info, see the documentation on the prop() and data() methods.

    Also, because you're binding to lots of elements, you might want to research and use event delegation. For jQuery version >= 1.7 see on(), and for older versions see delegate().