Happylab Logo
Published on

Day5: Flex Panels

Authors
js30

Project Introduction: Practice using CSS flex and JavaScript to create an image expansion effect on click.

Project Page: https://iris1114.github.io/javascript30/05_Flex-Panel-Gallery/index.html

1. Implementation:

  • Use flex for layout
  • Add two effects when clicking an image
  • Two effects: Image enlargement and text appearance

2. Layout Using Flex

Use flex to arrange the layout and use transform to move the first and last text elements outside the viewport.

/*  Add flex properties to panels */
.panels {
  display: flex;
}

/* Each panel has a ratio of 1
To center text vertically, direction is set to column */
.panel {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  cursor: pointer;
}

/* Move first and last p elements of panel outside viewport */
.panel p:first-child {
  transform: translateY(-100vh);
}

.panel p:last-child {
  transform: translateY(100vh);
}

3. Add Two Effects on Click

The two effects use the class names .open and .show-text.

/* Increase screen ratio */
.panel.open {
  font-size: 40px;
  flex-grow: 3;
}

/* Move text back to original position */
.panel.show-text :first-child,
.panel.show-text :last-child {
  transform: translateY(0px);
}

4. JavaScript Implementation

First get all panels, then toggle the CSS effects by adding the two class names when clicked.

const panels = document.querySelectorAll('.panel')

panels.forEach((panel) => {
  panel.addEventListener('click', () => {
    panel.classList.toggle('open')
    panel.classList.toggle('show-text')
  })
})

Wesbos's version uses transitionend, which triggers the toggleActive function when the CSS transition ends.

// wesbos's method
const panels = document.querySelectorAll('.panel')

function toggleOpen() {
  console.log('Hello')
  this.classList.toggle('open')
}

function toggleActive(e) {
  console.log(e.propertyName)
  if (e.propertyName.includes('flex')) {
    this.classList.toggle('open-active')
  }
}

panels.forEach((panel) => panel.addEventListener('click', toggleOpen))
panels.forEach((panel) => panel.addEventListener('transitionend', toggleActive))

5. References

https://developer.mozilla.org/en-US/docs/Web/CSS/transform https://developer.mozilla.org/en-US/docs/Web/API/Element/classList