Search code examples
jqueryremoveclass

jquery removeClass 'works' but effects of the class continues


First keep in mind I'm new in web design, JS and all this, please. Any suggestion will be appreciated :) I have this img icons (serviceIcon) positioned 'absolute' with their particular class (serviceHardware, ...).

<div class="servicesBox">
    <img class="serviceIcon serviceHardware" />
    <img class="serviceIcon serviceSoftware" />
    <img class="serviceIcon serviceNetwork" />
</div>

It's simple: mouseover changes opacity in not hovered items and resizes the hovered one; mouseleave animates all to their previous state; a click animates the clicked img to the corner, SHOULD remove serviceIcon class (to avoid triggering mouseover/mouseleave, right?) and moves down (in the example) the non clicked img, and adding serviceSelected class to the clicked item.

$("img.serviceIcon").click(function(){

    $("img.serviceIcon").not(this)
        .animate({
            top:'45px',
        });

    $(this).removeClass("serviceIcon")
        .animate({
            left:'150px'
        }, 300, function(){
            origLeft = $(this).css('left');
            $(this).addClass("serviceSelected");
            //alert(origLeft);
        });
});

BUT as you can see right here (http://jsfiddle.net/rcvmQ/4/), the clicked img keeps triggering mouseover/mouseleave events corresponding to serviceIcon class (already removed when clicking), and if you inspect the element you will see it doesn't have serviceIcon class anymore. What am I doing wrong here? May be all? idk.

Actually, it adds the serviceSelected class, but if you click it, never triggers the click event of this class. Weird. I've tested this in firefox and safari and both behave the same.

I have added extra validation code checking in the click event of serviceItem whether it has serviceSelected class, wich is NOT LOGICAL at all. I refuse to use it even if it works!! Thank you!

Edit: Code about mouseover/mouseleave

$("img.serviceIcon").mouseover(function(){
    $(".serviceIcon").not(this)
                        .animate({
                            opacity:'0.3'
                        }, 100);
    $(this).animate({
        width   :'25px',
        height  :'40px',
        opacity :1
    },200);
});

$("img.serviceIcon").mouseleave(function(){
$("img.serviceIcon").stop(true,true)
                        .animate({
                            width   :'20px',
                            height  :'40px',
                            opacity :'1'
                        },100);
});

Solution

  • Unbind the mouseover event

    http://jsfiddle.net/rcvmQ/5/

       $(this).off('mouseover').removeClass("serviceIcon")
                .animate({
                    left:'150px'
                },300, function(){
                    origLeft = $(this).css('left');
                    $(this).addClass("serviceSelected");
                    //alert(origLeft);
                });