3

I am trying to change the size of grid-template-columns upon the click of a button (https://jsfiddle.net/3ft6svgk/2/).

html:

<div class="grid-squares">
  <div class="grid_item">
    <h2>Lorem Ipsum</h2>
    <button id="firstButton">Learn More</button>
  </div>
   <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
   <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>  
   <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
</div>

css:

.grid-squares{
  display: grid;
  grid-template-columns: 1fr 1fr; 
  grid-auto-rows: 300px;
}

javscript:

firstButton = document.getElementById("firstButton")
firstButton.onclick = function(){
  squaresGrid = document.getElementsByClassName("grid-squares");
  squaresGrid.style.gridTemplateColumns = "1000px";
}

With this code I am getting

"Uncaught TypeError: Cannot set property 'gridTemplateColumns' of undefined
    at HTMLButtonElement.repairsAndUpgradesButton.onclick"

in the console. How can I properly change the value of grid-template-columns?

2 Answers 2

3

try this:

firstButton = document.getElementById("firstButton")
firstButton.onclick = function(){
  squaresGrid = document.getElementsByClassName("grid-squares");
  squaresGrid[0].style.gridTemplateColumns = "1000px";
}
Sign up to request clarification or add additional context in comments.

Comments

1

.getElementsByClassName() returns a NodeList collection of elements.

You either need to loop over your .gridSquares:

squaresGrid = document.getElementsByClassName("grid-squares");
for (let i = 0; i < squaresGrid.length; i++) {
   squaresGrid[i].style.gridTemplateColumns = "1000px";
}

Or access them by index (you only have one, at index 0):

squaresGrid = document.getElementsByClassName("grid-squares")[0];
squaresGrid.style.gridTemplateColumns = "1000px";

You will also want to make use of Unobtrusive JavaScript, and add an event listener to your button rather than make use of .onclick.

This can be seen in the following working example:

firstButton = document.getElementById("firstButton")
firstButton.addEventListener('click', function() {
  squaresGrid = document.getElementsByClassName("grid-squares")[0];
  squaresGrid.style.gridTemplateColumns = "1000px";
});
.grid-squares {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 300px;
}
<div class="grid-squares">
  <div class="grid_item">
    <h2>Lorem Ipsum</h2>
    <button id="firstButton">Learn More</button>
  </div>
  <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
  <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
  <div class="grid_item">
    <h2>Lorem Ipsum</h2>
  </div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.