Andrew Andrew - 1 year ago 99
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() {;

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 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?


Answer Source

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:


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') {;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download