Design comparison
Solution retrospective
I am still a beginner with javascript. Please I would like to know if there is a better way to write the javascript code.
Community feedback
- @lipe11Posted over 2 years ago
Hi, your solution looks pretty good!
I looked at your code, and I'll leave a couple of javascript ideas that hope you find useful.
Try to separate your DOM manipulation into functions. For example, if you find that you use too often something like this
document.querySelector('.when-clicked').style.display = "none";
you could introduce functions similar to this
function hide(selector) { document.querySelector(selector).style.display = "none"; }
and use them like this
hide('.when-clicked');
Avoid using DOM elements as data, instead put data in variables and update the DOM when data changes.
For example, instead of operating directly on an element like this
function minus() { document.getElementsByClassName("num")[0].innerHTML--; document.getElementsByClassName("num")[1].innerHTML--; // ... } function plus() { document.getElementsByClassName("num")[0].innerHTML++; document.getElementsByClassName("num")[1].innerHTML++; // ... }
you could operate on a variable and and update the DOM when the variable changes
let quantity = 0 function minus() { quantity--; updateDOM(); } function plus() { quantity++; updateDOM(); } function updateDOM() { const nums = document.getElementsByClassName("num"); for (let num of nums) { num.innerHTML = quantity; } }
lastly, leverage the power of fors when applicable, its easier than going through each element in an array.
Hope this is useful and gives you some ideas for your next challenge.
Marked as helpful0@PraiseImmanuelPosted over 2 years ago@lipe11 Thank you, sir, I will pay attention to everything you said.
0
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord