John Smith
John Smith

Reputation: 107

Can't change element class on click

Tell me please why div with id AudioVol+..(ex.1,2,3 and other) dont change class name when click on element with class name option_audio_player_mute?

Also tell me, can I reduce/refactor my code?

$('.option_audio_player_mute').live('click', function () {
    var idn = this.id.split('+')[1];
    var vol1 = $('#AudioVol1+' + idn);
    if ($(this).hasClass('audio_mute')) {
        vol1.removeClass('audio_vol_not_active').addClass('audio_vol_active');
    } else if ($(this).hasClass('audio_not_mute')) {
        vol1.removeClass('audio_vol_active').addClass('audio_vol_not_active');
    }
});

why doesn't this work?

Upvotes: 3

Views: 203

Answers (2)

xdazz
xdazz

Reputation: 160893

You could use .toggleClass, and use .on instead of .live.

$(document).on('click', '.option_audio_player_mute', function() {
    var vol1 = $("#AudioVol1\\+" + this.id.split('+')[1]), 
        $this = $(this);
    vol1.toggleClass('audio_vol_active', $this.hasClass('audio_mute'))
        .toggleClass('audio_vol_not_active', $this.hasClass('audio_not_mute'));
});

Upvotes: 1

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263047

The + sign has a special meaning in CSS (and jQuery) selectors: it is used to specify adjacent sibling selectors.

Try escaping the + sign in your id selector with two backslashes:

var vol1 = $("#AudioVol1\\+" + idn);

Upvotes: 1

Related Questions