Search code examples
jquerytoggleclass

toggleClass is not working as expected : function is calling twice


ToggleClass is not giving expected result because the function is executing twice.

HTML:

<form method="get" class="custom-controls">
    <label><input name="Gorilla" type="checkbox"/>Gorilla</label><br/>
    <label><input name="Lamb" type="checkbox"/>Lamb</label><br/>
    <label><input name="Tiger" type="checkbox"/>Tiger</label><br/>
    <input type="submit">
</form>    

jQuery:

$(document).ready(function(){
    $('.custom-controls').find('input').each(function(){
        ($(this).is(':radio')?$input_class_name="custom-radio-wrap":$input_class_name="custom-check-wrap");     
        $(this).parents('label').wrapInner(('<span class="' + $input_class_name + '"></span>'));                    
    });
    $('.custom-controls').delegate("span", "click", function () {
        $(this).toggleClass('checked');     
    });
});

FIDDLE REFERENCE


Solution

  • This is caused by event bubbling, just add a return false after it.

    $('.custom-controls').delegate("span", "click", function () {
        $(this).toggleClass('checked');
        return false; 
    });
    
    OR
    
    $('.custom-controls').delegate("span", "click", function (e) {
        $(this).toggleClass('checked');
        e.preventDefault();                                                    
    });