dimanche 1 novembre 2020

Unwanted 1 second lag after click event with javascript

I have javascript code that toggles from radio button 1 to radio button 2 when the user clicks anywhere on a box. It works, but only after a lag of 1 second or so. There will be a hundred of these boxes, so this lag really kills the user experience. Any clue where does this lag come from?

Note: if I remove the loop, and I target the elements with their unique ID's instead of looping through "all elements with class x", then the lag disappears. But I need the loop, considering there will be a hundred of those boxes...

Here is the javascript:

$('.checkbox-oui-non').click(function(evt) {
    var a = document.querySelectorAll(".checkbox-oui-non");
    var b = document.querySelectorAll(".checkbox-oui-non .oui");
    var c = document.querySelectorAll(".checkbox-oui-non .non");
    
    for (i = 0; i < a.length; i++) {
        if (b[i].checked ||
        c[i].checked) {
            if (b[i].checked) {
                b[i].checked = false; 
                c[i].checked = true;
            }
            else if (c[i].checked){
                b[i].checked = true; 
                c[i].checked = false;
                }
        } else {    
            b[i].checked = true;
        }
    }
});

and the html:

<div class="checkbox-oui-non">
    <span>L'enfant est né d'une précédente union</span>
    <div class="oui-non-toggle-wrapper">
        <div class="checkbox">
            <input type="radio" id="moi_oui" name="moi" class="oui">
            <label for="moi_oui">oui</label>
        </div>
        <div class="checkbox">
            <input type="radio" name="moi" id="moi_non" class="non">
            <label for="moi_non">non</label>
        </div>
        <div class="oui-non-toggle"></div>
    </div><!-- end of oui-non-wrapper -->
</div><!-- end of checkbox-oui-non -->

Thank you so much for your help!




Aucun commentaire:

Enregistrer un commentaire