Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid the start of a function if a condition is not fulfill in javascript

I would like the user not to be able to click on the second button if the first one was not clicked.
I thought about using a condition with a bullet but I can’t find the right way to set it up.
I share the code with you :

HTML :

<style>
    .enable{
        background-color: orangered;
        pointer-events: auto;
        cursor: pointer;
    }

    .disable{
        background-color: gray;
        pointer-events: none;
    }


</style>
<button id="Act1" class="enable" type="button">1</button>
<button id="Act2" class="disable" type="button">2</button>

JS :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let act1 = document.getElementById('Act1')
let act2 = document.getElementById('Act2')
let clickTrue1 = false


function act1Clicked(){
    clickTrue1 = true;
    act2.classList.remove("disable");
    act2.classList.add("enable");
    localStorage.setItem('btn2-enabled', true);
}

if (localStorage.getItem('btn2-enabled'))
    act1Clicked();
act1.addEventListener('click', act1Clicked);


if (clickTrue1 === true) {
    function act2Clicked(){
        act3.classList.remove("disable");
        act3.classList.add("enable");
        localStorage.setItem("btn3-enabled", true);
    }

    if(localStorage.getItem("btn3-enabled"))
        act2Clicked();
    act2.addEventListener('click', act2Clicked);
}

I think my problem is that when I set my clickTrue1 to true, the true stays in my function?

Thanks !

>Solution :

function act2Clicked(){
    if (clickTrue1 !== true) return;

    act3.classList.remove("disable");
    act3.classList.add("enable");
    localStorage.setItem("btn3-enabled", true);
}

Remove the wrapping if statement and just exit from the function if clickTrue1 is not true

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading