Why my button doesn't work?

I would like to have my button changing the size of the div to 200px and then when I click again make the div resize to its original size, I dont know what Im doing wrong , Im using classes because I want to use the same class for more than one div later, thanks guys
codepen
HTML

    <div id="div1" class="div1">
        <button id="div1Btn">My button</button>
        <div id="subDiv1" class="subDiv1">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, enim maiores praese
            fugiat eum iste qui ullam vero natus itaque odit doloribus. Id accusamus, amet hic voluptas 
            placeat sapiente obcaecati!</p>
        </div>
    </div>

CSS

.subDiv1 {
    background-color: blueviolet;
    width: 300px;
    height: 200px;
    margin: 10px;
}
.smoth {
    transition: all .5s linear;
  }

JS

window.onload = myFunction;
document.getElementById("div1Btn").addEventListener("click", myFunction)
function myFunction() {
    for (var i = 0, y = subDiv1.length; i < y; i++) {
        var subDiv1 = document.getElementsByClassName("subDiv1");
        if (subDiv1[i].style.width == "300px") {
            subDiv1[i].style.width = "200px";
            subDiv1[i].className = "smoth";
        }
        else {
            subDiv1[i].style.width = "300px";
        }
    }
}

Put this line var subDiv1 = document.getElementsByClassName("subDiv1"); outside of the loop, because subDiv1.length will be undefined. (trying to access variable before it exists).

// some code..
var subDiv1 = document.getElementsByClassName("subDiv1");
for (var i = 0, y = subDiv1.length; i < y; i++) {
    // some code..
}
// some code..

Also, Remove line subDiv1[i].className = "smoth"; and button will start working as expected.

Complete Code (JS)

I’ve made following changes in JS.

window.onload = myFunction;
document.getElementById("div1Btn").addEventListener("click", myFunction);
function myFunction() {
  var subDiv1 = document.getElementsByClassName("subDiv1");
  for (var i = 0, y = subDiv1.length; i < y; i++) {
    if (subDiv1[i].style.width == "300px") {
      subDiv1[i].style.width = "200px";
    } else {
      subDiv1[i].style.width = "300px";
    }
  }
}
1 Like

thank so much for your answer I did the same exercise lastnight but only using one id so I didnt have the need to use my for loop thats what made everything kind of tricky, thanks for your help

1 Like

I’m glad I could help you buddy :heart:

1 Like