Hello guys,
I have completed Responsive Web Design Certification and now I am learning JavaScript. I am trying to complete ‘Build 15 JavaScript Projects’ of John Smilga.
I have developed my first JavaScript project on Color Flipper.
You can switch between the ‘Simple’ and ‘Hex’ functionalities and click on the button to flip over the colors.
Hope you guys like it and I would like to know your feedback . Kindly suggest if any improvements can be made.
Hello~!
I tested it out a little, and it seems that the Simple
option is non-functioning? It looks like you’ve coded an event listener that calls the simEvent
function, but I don’t see the simEvent
function itself.
Hi @nhcarrigan,
Thanks for checking out the project. You can find the simEvent function at line number 10 of JS.
When you click on Simple and then click on the Click Me button, color flips between a predefined set of colors that I have specified in the code.
However, if you click on Hex and then the Click Me button, it randomly generates a Hex Code and displays the Hex code and the corresponding background color.
Ah, I see what’s going on now - the “click me” button appears not to do anything until I’ve selected an option up top. If I select the “simple” option, then it works as intended. Then, if I select the “hex” option, it works with hex values as intended. But if I click the “simple” option again, it seems to continue using hex values.
You are attaching two event listeners to the same button. You can remove the currently attached listener before adding the new.
function simEvent(e) {
hclbtn.removeEventListener("click", hclkEvent);
sclbtn.addEventListener("click", runEvent);
}
function hexEvent(b) {
sclbtn.removeEventListener("click", runEvent);
hclbtn.addEventListener("click", hclkEvent);
}
I would also suggest adding the simple listener on page load so the button always has an event listener (you can just call simEvent() at the bottom).
Thanks @nhcarrigan for pointing out that and @lasjorg for the idea and suggestions.
I have now added the removeEventListener and it works as intended. I will work on adding the simple listener on page load.
Thank you so much guys for your help and feedback