JavaScript/jQuery .click() issue with buttons

48 Views Asked by At

I'm doing The Odin Project's JavaScript/jQuery project in its Web Development 101 course. I am building an "etch a sketch" app using divs as squares on a grid that change color when the mouse passes over them. For my final option, I would like to leave a trail of fading blocks. This works when I press my button. HOWEVER, when I select a different option, after selecting the "Leave a trail" one, the trail of fading divs automatically is added to the others as well. I need to know if there is a way to end the function once a different button is pressed. Also, I'm a beginner and am just learning this language and framework. Thank you in advance!

$(".trail").click(function() {
    $(".grid").mouseenter(function() {
        $(this).css("background-color", "black");
        $(this).fadeTo(0, 0);
        $(this).mouseleave(function() {
            $(this).fadeTo(600, 1);
        });
    });
});
1

There are 1 best solutions below

1
Arun P Johny On

You should remove the mouseenter handler from the grid element once another button is clicked, so something like

$(".trail").click(function() {
    $(".grid").on('mouseenter.trail', function() {
        $(this).css("background-color", "black");
        $(this).fadeTo(0, 0);
        $(this).mouseleave(function() {
            $(this).fadeTo(600, 1);
        });
    });
});

then in other button clicks, you can remove this handler using .off()

$(".grid").off('mouseenter.trail')

The namespaces are used in the event registration and removal so that by mistake we don't remove any other handlers