Social Media Carousel with Scroll-Driven Animations

Hello Coder! Welcome to Codewithshobhit Blog. Today we are going to Create Social Media Carousel with Scroll-Driven Animations  


Project Folder Structure:

  • Create a file called  index.html  to serve as the main file.

  • Create a file called  style.css  for the CSS code.
  • Create a file called  script.js  for the JavaScript code.

HTML CODE

HTML
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Social Media Carousel - Scroll-Driven Animations API</title>
    <link
      href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <section>
      <header>
        <img
          src="https://assets.codepen.io/9518566/internal/avatars/users/default.png?fit=crop&format=auto&height=512&version=1674234350&width=512"
          alt="profile image"
        />
        <div>
          <p>Codewithshobhit</p>
          <i class="ri-verified-badge-fill"></i>
        </div>
      </header>
      <div class="card">
        <div id="carousel" class="visual">
          <img
            id="card1"
            src="https://e0.pxfuel.com/wallpapers/371/492/desktop-wallpaper-nancy-momoland-nancy-momoland-nancy-jewel-nancy-jewel-mcdonie.jpg"
            alt="Cute dogs"
          />
          <img
            id="card2"
            src="https://i.pinimg.com/1200x/52/b7/f6/52b7f6d845ed8b40112603c2550ec14a.jpg"
            alt="Cute dogs"
          />
          <img
            id="card3"
            src="https://i.pinimg.com/474x/19/9f/05/199f0595fe20ca4c828affdf7c8e437a.jpg"
            alt="Cute dogs"
          />
          <img
            id="card4"
            src="https://image.kpopmap.com/2019/03/momoland-ready-or-not-member-profile-Nancy.jpg"
            alt="Cute dogs"
          />
          <img
            id="card5"
            src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/3e/Nancy_jewel_Mcdonie.jpg/604px-Nancy_jewel_Mcdonie.jpg"
            alt="Cute dogs"
          />
          <img
            id="card6"
            src="https://cdn4.sharechat.com/hot_7c8ddac_1613034757053_sc_cmprsd_40.jpg?tenant=sc&referrer=pwa-sharechat-service&f=rsd_40.jpg"
            alt="Cute dogs"
          />

          <div class="controls">
            <button
              id="prev"
              class="previous"
              onclick="carousel.scrollBy(-100, 0)"
            >
              <i class="ri-arrow-left-circle-fill"></i>
            </button>
            <button id="next" class="next" onclick="carousel.scrollBy(100, 0)">
              <i class="ri-arrow-right-circle-fill"></i>
            </button>
          </div>

          <div id="pagination" class="pagination"></div>
        </div>
      </div>
      <div class="social">
        <div class="inter">
          <div>
            <button>
              <i class="ri-heart-line"></i>
            </button>

            <button>
              <i class="ri-chat-3-line"></i>
            </button>
            <button>
              <i class="ri-share-line"></i>
            </button>
          </div>

          <button>
            <i class="ri-bookmark-line"></i>
          </button>
        </div>

        <p>3,802 likes</p>
        <p>Love😘💓</p>
      </div>
    </section>
  </body>

Explanation Of HTML CODE

  1. Metadata: Defines metadata for the HTML document, including character set, viewport settings, and the document title.

  2. Stylesheets: Links to external stylesheets, including Remixicon for icons and a custom stylesheet (style.css).

  3. Body Content: Contains the main content of the page wrapped in a <section> element. Inside this section:

    • Header: Displays a user profile image, username, and a verified badge icon.
    • Card: Contains a carousel (#carousel) with a series of images. The images have unique IDs (card1 to card6), and navigation buttons (#prev and #next) are provided to scroll through the carousel. Pagination dots are represented by the #pagination element.
    • Social Section: Displays social interaction buttons (like, comment, share, and bookmark), along with the number of likes and a caption.

CSS CODE

CSS
@import 'https://unpkg.com/open-props' layer(design.system);
@import 'https://unpkg.com/open-props/normalize.dark.min.css'
  layer(demo.support);

@import url('https://fonts.googleapis.com/css2?family=Inter:wght@200..900&display=swap');

@layer demo.base {
  :root {
    font-family: 'Inter', sans-serif;
    --sm-font-size: 0.875rem;
    --size: min(470px, 100dvw);
  }
  body {
    display: grid;
    place-content: center;
    background-color: black;
    padding-block: var(--size-fluid-3);
  }
  section {
    display: grid;
    justify-content: center;
    gap: var(--size-2);

    & header {
      display: flex;
      align-items: center;
      gap: var(--size-2);

      > img {
        inline-size: 2.5rem;
        aspect-ratio: var(--ratio-square);
        border-radius: var(--radius-round);
      }

      & p {
        font-size: var(--sm-font-size);
        font-weight: var(--font-weight-6);
      }

      & i {
        color: var(--blue-5);
      }

      > div {
        display: flex;
        align-items: center;
        gap: var(--size-1);
      }

      @media (width < 468px) {
        padding-inline: var(--size-3);
      }
    }

    .card {
      display: flex;
      flex-direction: column;
      gap: var(--size-3);
      position: relative;

      & button {
        background: transparent;
      }

      .visual {
        display: grid;
        grid-auto-flow: column;
        grid-auto-columns: var(--size);
        inline-size: var(--size);
        block-size: var(--size);
        overflow-x: auto;

        /* Hide scrollbar */
        -ms-overflow-style: none; /* IE and Edge */
        scrollbar-width: none; /* Firefox */
        &::-webkit-scrollbar {
          display: none;
        }

        & img {
          inline-size: var(--size);
          border-radius: var(--radius-1);
          border: var(--border-size-1) solid var(--stone-11);
        }
      }

      .controls {
        position: absolute;
        z-index: 1;

        inset-inline: var(--size-2);

        inset-block-start: 50%;
        display: flex;
        justify-content: space-between;
      }

      & button {
        inline-size: var(--size-8);
        border-radius: var(--radius-round);
        aspect-ratio: var(--ratio-square);
        font-size: 1.75rem;

        display: inline-flex;
        align-items: center;
        justify-content: center;
        padding: 0;
        box-shadow: var(--shadow-1);
        color: var(--stone-1);
        transition: color 0.2s ease;

        &:hover {
          color: var(--stone-2);
        }
      }
    }

    .pagination {
      position: absolute;
      z-index: 1;
      inset-inline: 0;
      inset-block-end: var(--size-5);

      display: flex;

      justify-content: center;
      gap: var(--size-1);

      & button {
        display: inline-flex;
        place-content: center;
        inline-size: 0.5ex;
        flex-shrink: 0;
        aspect-ratio: var(--ratio-square);
        border-radius: var(--radius-round);
        background-color: hsl(0 0% 100%/ 60%);
      }
    }

    .social {
      display: grid;
      gap: var(--size-1);
      & button {
        background-color: unset;
        font-size: var(--font-size-3);
        padding: 0;
      }

      .inter {
        display: flex;
        align-items: center;
        justify-content: space-between;

        > div {
          display: flex;
          gap: var(--size-3);
        }
      }

      & p {
        font-size: var(--sm-font-size);
        font-weight: var(--font-weight-6);
      }
      @media (width < 468px) {
        padding-inline: var(--size-3);
      }
    }
  }
}

@layer demo.scroll-driven-animation {
  .visual {
    scroll-snap-type: x mandatory;
    overscroll-behavior: contain;
    scroll-behavior: smooth;
    scroll-timeline: --carousel inline;

    > * {
      scroll-snap-align: center;
    }

    & img {
      view-timeline-axis: inline;
      perspective: var(--size);
    }
  }

  .pagination > button {
    /* every dot use the scale animation */
    animation: scale linear both;
  }

  .next {
    animation: auto next ease;
    animation-timeline: --carousel;
  }

  .previous {
    animation: auto prev ease;
    animation-timeline: --carousel;
  }
}

/* pagination dots effect */
/* scaled out, until in view, then scale 1 */
@keyframes scale {
  0%,
  100% {
    scale: 0.75;
  }
  50% {
    scale: 1;
    background-color: white;
  }
}

@keyframes prev {
  from {
    visibility: hidden;
  }
}

@keyframes next {
  to {
    visibility: hidden;
  }
}

Explanation Of CSS CODE

  1. Imports: Imports external stylesheets for font (Inter), icons (Remixicon), and a design system (open-props).

  2. Styling Rules: Defines various styling rules for different elements in the HTML. It uses custom properties for sizing, colors, and other design aspects. The styles are organized into layers (demo.support, demo.base, demo.scroll-driven-animation).

  3. Media Queries: Includes media queries to apply specific styles based on the screen width (e.g., adjusting padding for smaller screens).

  4. CSS Keyframes:

    • scale: Defines a keyframe animation for scaling pagination dots.
    • prev and next: Define keyframe animations for the previous and next buttons' visibility.

JS CODE

JS
/*
  This script is specifically designed to dynamically generate pagination markers for the carousel.
  The actual animation logic is handled using the CSS version of the Scroll-driven Animations API.
*/
const images = document.querySelectorAll('#carousel img');
const pagination = document.querySelector('#pagination');

function createPaginationMarkers() {
  images.forEach((img) => {
    const imgViewName = `--${img.id}`;
    img.style.viewTimelineName = imgViewName;
    const marker = document.createElement('button');
    marker.type = 'button';
    marker.role = 'tab';
    marker.style.animationTimeline = imgViewName;
    marker.addEventListener('click', () =>
      img.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start',
      })
    );
    pagination.appendChild(marker);
  });

  document.body.style.timelineScope = `${Array.from(images).map(
    (image) => image.style.viewTimelineName
  )}`;
}

// Check browser support for Scroll-driven Animations
if (CSS.supports('view-timeline-axis', 'inline')) {
  createPaginationMarkers();
}

// Start scrolling from the second image
carousel.scrollBy(100, 0);

Explanation Of JS CODE

  1. Script Purpose: The script dynamically generates pagination markers for the carousel images using the Scroll-driven Animations API.

  2. DOM Selection: Selects all images inside the #carousel element and the #pagination element.

  3. Pagination Marker Creation: The createPaginationMarkers function iterates through each image, assigns a unique view timeline name (--${img.id}), and creates a corresponding button for pagination. Each button has a click event listener that scrolls the associated image into view.

  4. Browser Support Check: Checks if the browser supports the Scroll-driven Animations API using CSS.supports. If supported, it calls the createPaginationMarkers function.

  5. Initial Scroll: Scrolls the carousel to the second image (carousel.scrollBy(100, 0)).

Live Preview 


See the Pen Social Media Carousel with Scroll-Driven Animations by Codewithshobhit (@Codewithshobhit) on CodePen.

Conclusion

In conclusion, the provided code creates a visually appealing and interactive social media carousel with scroll-driven animations using HTML, CSS, and JavaScript. The code incorporates external libraries for styling and icons, and it leverages the Scroll-driven Animations API for a smooth scrolling experience. The structure of the code is well-organized, with distinct sections for HTML content, CSS styling, and JavaScript functionality.

The HTML defines the layout, including a user profile header, an image carousel with navigation controls, and a social interaction section. The CSS employs a design system, custom properties, and media queries to ensure a consistent and responsive design across different screen sizes. The JavaScript dynamically generates pagination markers for each image in the carousel, providing users with a visual indication of their position within the content.

The use of keyframe animations in CSS enhances the user interface, with subtle effects on pagination dots and button visibility. The script also checks for browser support before applying the Scroll-driven Animations API, ensuring a graceful degradation in case of unsupported browsers.

Overall, the code demonstrates effective integration of HTML, CSS, and JavaScript to create an engaging social media carousel with modern design elements and smooth scroll-driven animations.

How to run this Html Css and Js Project in Our Browser?

first, you need a code editor either you can use VS code studio or notepad and then copy the html,css, and javascript code, create separate or different files for coding then combine them, after creating file just click .html file or run from VS Code studio and you can project preview.


Which Code Editor do you use to create those projects?

I am using VS Code Studio.


is this project responsive or not?

Yes! this project is a responsive project.

If you enjoyed reading this post and found it useful, please share it with your friends and follow me on Instagram.

Thanks for reading!

Author: Shobhit 😊