I want to make a toggle which toggles the height and the width of an element whenever it’s clicked.
<div class="flexbox-container" id="main" onclick="staybig()">Create Account</div>
.flexbox-container {
transition: height 0.5s, width 0.5s;
height: 100px;
width: 100px;
display: flex;
justify-content: center;
text-align: center;
align-items: center;
background-color: #492ee4;
border-radius: 50%;
display: flex;
margin: auto;
margin-top: 200px;
}
let isBig = false
if (isBig) {
main.style.width = "100px";
main.style.height = "100px";
isBig = false
} else {
main.style.width = "113px";
main.style.height = "113px";
isBig = true
}
This doesn’t work as expected. Can someone help me out, please?
Thank you
4
Answers
So this is where i call the function in html. And yes, the link to the JS file exists.
And this is the CSS
It looks like your code is not updating the isBig variable correctly. You need to move the isBig variable outside of the click event handler so that it retains its state between clicks. Here’s a corrected version of your code:
From your description of the problem and the code you provided, it would seem that you define
isBig
inside the event handler. This means what every time the event fires you re-set the state ofisBig
back tofalse
. Therefore the element can only be made larger.To fix this you need to define
isBig
outside of the event handler:That being said, a much better approach would be to define the styles in CSS and then just
toggle()
that class in the event handler, which you should bind in JS, not HTML. Here’s a working example with those fixed applied:Thank you so much guys!!!
Now it’s working. I always make this mistake. 😀