Assessment wanted for Events 1 skill test

i’m trying to create a function that will change the ‘machine is off’ to ‘machine is on’ on the button. here is a link to the test page and one to the codepan

Hi @sebastian_lazar!

Your code is correct so far… what you need to do is make the 2nd parameter of the addEventListener() function equal to a callback function that will check that state of your button. If it is in an “on” state, change it to an “off” state, and vice versa.

How you put it in an “on” or “off” state is up to you. You probably want to change the textContent on the button to indicate the state, and/or add a paragraph to the page, then content of which changes depending on whether it is on or off.

You might also want to have an indicator as to whether the machine is on or off, like a class name.

Have a think about this. If you are still not sure what to do, I will share the marking guide with you.

Thank you Chris,
i’ve added: const button = function() {this.textContent = “Machine is on”};
and this did it but now i have to figure out how to remove the event listener so it goes back to “Machine is off”.

Hi Chris,
no luck trying to remove the event listener. the button reads “Machine is on” but it won’t reverse to “Machine is off” even though i tried placing the remove event listener in and outside the anonymous function.
maybe you can take a look and give me some hints when you have a moment.

Hrm, you have got something a bit confused here. At no point do you need to remove the event listener — it needs to stay added to the button, but inside you need to use a conditional that checks what the current state of the button is, and then toggles it to be in the other state.

Try having a look at our marking guide for an idea of how to do this:

Hi Chris,
if i want to reset the text to the default text ‘Machine is off’ by clicking a second time on the button it doesnt work with the else if or else Statement after your example. It only works in one way. Can you pls help
I tried with following code:

let btn = document.querySelector(’.off’);

// Add your code here

function textChange() {
if(btn.className === ‘off’) {
btn.textContent = ‘Machine is on’;
} else {
btn.textContent = ‘Machine is off’;

btn.addEventListener(‘click’, textChange);

Thank you Chris,

yeah, i’m sorting things out and this definitely helps.

adopting and adapting to a different way of approaching things.

all the best

1 Like

Hi there @nevertolate!

You are definitely on the right track here; the main problem is that you are testing based on the class name on the button. When it is found to be “off”, you run the code inside the if block, but then the class name isn’t changed, so the machine is turned on, but then it will never turn off again because it is always the if part that is run, never the else part.

Have a look at our solution for this:

We are changing the classname, as well as the button text, so that it will toggle back and forth.