Design comparison
Solution retrospective
Hi there. I have a bit of an issue with the JavaScript. Everything works well only after clicking the toggle button twice. I don't understand why its behaving like it is. I'd appreciate any help I can get.
Community feedback
- @RoksolanaVeresPosted 11 months ago
Hey, I got a little curious about your issue with the toggle button and I think I've found the problem.
I saw that initially, you set the properties
display:block
anddisplay:none
to your.card-price
and.card-price-monthly
classes in a separate css file and when a user clicks the toggle button thepriceChange()
function is supposed to applystyle.display = none
to the elements that are displayed as blocks andstyle.display=block
to those withposition:none
.But the thing is that
style.display
looks for the inline styles of the elements, not in your css file. Thus, when you click the toggle button for the first time, the conditionelement.style.display === "none" ? "block" : "none"
will always return "none" even if in the css file this particular element also hasposition:none
and was supposed to change it toposition:block
.To solve the problem you can either specify these inline styles in your html for each price span, like:
<span class="card-price-monthly text-white" style="display: none" >$249.99 </span> <span class="card-price text-white" style="display: block" >$24.99 </span>
Or you can create an init function in your js file, where you set the initial inline styles for the price spans and then call this function.
function init() { monthPriceElements.forEach((element) => { element.style.display = "none"; }); yearPriceElements.forEach((element) => { element.style.display = "block"; }); } init();
I hope you've got the idea, but if my explanation doesn't make any sense, feel free to ask additional questions)
Marked as helpful0
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