Andrew Andrew - 29 days ago 11
jQuery Question

Removing a listener class doesn't stop a sound event associated Jquery Javascript

I'm playing a sound when hovering on an image (this is working fine already) and want to include a button to turn this off if desired. Unfortunately I haven't been able to make it work.

My current code goes like:

For creating the sound

//a bunch of code to generate the audio that ends on

var mouseoversound = createsoundbite('mysound.mp3')


For triggering it

$(".play").mouseover(function() {
mouseoversound.play();
});


The listener element

<%= image_tag "image.png", class:'logo-image play' %>


I thought that the simplest solution for disabling it was to remove the class 'listening' for the event (i.e. '.play') in the element listener, so I tired:

$(".sound").click(function(){
$(".logo-image").removeClass("play");
});

//.sound is the class of the button that's intended to block it.


Although the latter script does successfully remove the class 'play' the sound keeps playing every time I hover over the image. What am I missing? shouldn't the sound just stop playing?

Do you see any other solution to this?

Cheers

Answer

The issue is because the event handler is bound to the element. Removing the class after the event is bound does not affect that binding. To affect the event handler, you can call off(), like this:

$(".sound").click(function(){
    $(".logo-image").off('mouseover');
});

Alternatively, if you want to toggle the sound functionality based on the class, you can keep your current logic and check that the element still has the class in the mouseover handler:

$(".play").mouseover(function() {
    if ($(this).hasClass('play') {
        mouseoversound.play();
    }
});

$(".sound").click(function(){
    $(".logo-image").toggleClass("play");
});