I have a 2 x 2 CSS grid. Each grid item briefly describes a service (small business website) and each grid item has a button to learn more about said service. When a user clicks one of the four buttons to learn more, I would like that grid item to expand to take up the entire 2x2 grid (this I have working) and for the other 3 grid items to disappear (this I am having trouble with). Here is an example: https://jsfiddle.net/L7fatdmh/ , note that only the first grid item has JS applied to it at the moment.
html:
<div class="grid-squares">
<div class="grid_item" id="g1">
<h2>Service One</h2>
<p>
lorem impsum
</p>
<button id="firstButton">Learn More</button>
</div>
<div class="grid_item">
<h2>Service Two</h2>
<p>
lorem impsum
</p>
<button>Learn More</button>
</div>
<div class="grid_item">
<h2>Service Three</h2>
<p>
lorem impsum
</p>
<button>Learn More</button>
</div>
<div class="grid_item">
<h2>Service Four</h2>
<p>
lorem impsum
</p>
<button>Learn More</button>
</div>
</div>
css:
.grid-squares{
display: grid;
grid-template-columns: 1fr 1fr;
grid-auto-rows: 300px;
}
js:
firstButton = document.getElementById("firstButton");
firstButton.onclick = function(){
squaresGrid = document.getElementsByClassName("grid-squares");
g1 = document.getElementById("g1");
console.log(g1)
g1.style.gridColumn = "1/3";
g1.style.gridRow = "1/3";
}
As you can see in the jsFiddle example, the grid item does expand to fill the proper space, but all of the other grid items are still visible underneath. How can I hide these? Is initially hiding all grid-item
s and then displaying a specific item based on it's id
(i.e g1
in the first grid item) the best option?
答案 0 :(得分:0)
You can select the elements that are not your event target and hide them.
Using your fiddle, if we add
gOther = document.querySelectorAll(".grid_item:not(#g1)");
for (g of gOther) {
g.style.display = "none";
}
It would work, but for a real world scenario you would need to make this a little bit more complete and look for elements that are not your target.