Geek Logbook

Tech sea log book

50projectsIn50days – Day 6: Scroll Animation

The Scroll Animation is a scroll that has a fixed number of contents inside the html. So, it’s not generated dynamically. In the case of this project there are 12 Boxes. Each h2 box has a class “Box” that gives the square aspect as you can see in this CSS:

.box {
    background-color: seagreen;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 400px;
    height: 200px;
    margin: 10px;
    border-radius: 10px;
    box-shadow: 2px 4px 5px rgba(0, 0, 0, 0.3);
    transform: translateX(400%);
    transition: transform 0.4s ease;

Talking about animation, which is the central part of the project. After selecting all the boxes with the querySelectorAll('.box') we create, at the end, the condition to test if the box is going to be shown or not. In fact, the part of the code is quite straightforward:

        boxes.forEach(box => {
            const boxTop =box.getBoundingClientRect().top

            if(boxTop < triggerBottom) {
            } else {

Then we have to know how we can handle the distances in the screen without a library. This is possible thanks to the use of the function: getBoundingClientRect() which:

The Element.getBoundingClientRect() method returns a DOMRect object providing information about the size of an element and its position relative to the viewport.


And if we go to see what is a DOMRect we’ll find:

DOMRect describes the size and position of a rectangle.

DOMRect Documentation

Therefore, with the function getBoundingClientRect() we can know where the Top is. As we can se in the constant boxTop.

If the top is less than the trigger bottom we’ll add the class show, else we remove it. Show is a simple translation: {
    transform: translateX(0);

You can see the code in this GitHub Repository: 06.scroll_animation and the demo of the project is here: Scroll Animation

Leave a Reply

Your email address will not be published. Required fields are marked *.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>