0

I was looking for how to disable button using JS and I find this and it works:

<button id="startbtn" onclick="this.disabled=true; pausebtn.disabled=false; stopbtn.disabled=false;">Start</button>

but I want to disable it using addEventListener() method instead of doing it directly on the html div, but it is not working, is it posible?

let start1 = document.getElementById('startbtn');
        start1.addEventListener('click', start);
        start1.addEventListener('click', this.disabled = true);

Obs: the second line in the code above starts the "start" function which is a cronometer.

2 Answers 2

4

You need to pass a callback.

If you didn't already have a reference to the button use the currentTarget property of the event object that gets passed into the callback.

start1.addEventListener('click',() => start1.disabled = true);
Sign up to request clarification or add additional context in comments.

2 Comments

You should update your explanation since you're not using currentTarget 😜 This is easier to read. You would only use currentTarget if you didn't already have a reference or if you wanted to make your handler reusable.
Haha! Thanks friend. Forgot to update it after the updating the code :)
2

You can use Element.currentTarget.setAttribute(name, value) method more details about the function here.

let start1 = document.getElementById('startbtn');
start1.addEventListener('click', start);
start1.addEventListener('click', (e) => e.currentTarget.setAttribute('disabled', true));

It is tested & working.
let me know if you have any issues with the snippet above.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.