Is there a way to instruct gsap and js to execute a certain task solely when the width exceeds 1200px?

Having some trouble with my project. I'm attempting to implement a horizontal scroll using Javascript and GSAP, but only if the width is greater than 1200px. I've managed to get it working somewhat, but when I resize the webpage to a smaller width, the horizontal scroll remains. Apologies for any language issues and would appreciate any help!

const aboutContainer = document.querySelector(".about__container");
const aboutContent = gsap.utils.toArray(".about__container .about__content");
const aboutMask = document.querySelector(".about__mask");
if (document.body.clientWidth > 1200) {
  let scrollTween = () => {
    gsap.to(aboutContent, {
      xPercent: -100 * (aboutContent.length - 1),
      ease: "none",
      scrollTrigger: {
        trigger: ".about__container",
        pin: true,
        scrub: 1,
        end: "+=3000",
      },
    });

    gsap.to(aboutMask, {
      width: "100%",
      scrollTrigger: {
        trigger: ".about__section",
        start: "top left",
        scrub: 1,
      },
    });

    let tl = gsap.timeline({
      scrollTrigger: {
        trigger: ".about__container",
        start: "center bottom",
      },
    });

    tl.from(aboutContent, { x: 300, opacity: 0, duration: 1 });
  };
  scrollTween();
};

Answer №1

If you have specific goals in mind, gsap.matchMedia allows you to control when a set of instructions should run based on the client size and browser width. You can choose to execute certain actions only when the browser is resized to the desired dimensions.

const aboutContainer = document.querySelector(".about__container");
const aboutContent = gsap.utils.toArray(".about__container .about__content");
const aboutMask = document.querySelector(".about__mask");

let mm = gsap.matchMedia();

// define a media query. The specified function will be executed when the condition is met
mm.add("(min-width: 800px)", () => {
  let scrollTween = () => {
    gsap.to(aboutContent, {
      xPercent: -100 * (aboutContent.length - 1),
      ease: "none",
      scrollTrigger: {
        trigger: ".about__container",
        pin: true,
        scrub: 1,
        end: "+=3000",
      },
    });

    gsap.to(aboutMask, {
      width: "100%",
      scrollTrigger: {
        trigger: ".about__section",
        start: "top left",
        scrub: 1,
      },
    });

    let tl = gsap.timeline({
      scrollTrigger: {
        trigger: ".about__container",
        start: "center bottom",
      },
    });

    tl.from(aboutContent, { x: 300, opacity: 0, duration: 1 });
  };
  scrollTween();
  return () => {
    // any optional cleanup tasks here?
  }
});
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9beaab8a999eaf7e8ebf7ec">[email protected]</a>/dist/gsap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b5c485a4b7b08150a09150e">[email protected]</a>/dist/ScrollTrigger.min.js"></script>
<div class="about__container">
  <div class="about__content">
    About Content
    <div class="about__section">
  </div>
  About Container
</div>
<div class="about__mask">About Mask</div>

For the boilerplate code for matchMedia, visit:

Answer №2

Effortless Styling with CSS

If you are not keen on using JavaScript and GSAP to achieve the desired effect, then this simple CSS method might be just what you need.

In case you prefer simplicity: typically, utilizing CSS media queries can offer a more straightforward solution.

To restrict scrolling to only occur when the screen width is greater than 1200px, assuming overflow starts at that point, this uncomplicated CSS approach will get the job done efficiently.

.container {
/*adjust container width to match device/screen width*/
width: 100%; 

/*initially hide horizontal overflow to prevent unnecessary scrolling*/
overflow-x: hidden; 
}

@media only screen and (min-width: 1200px){
/*if device/screen width is >=1200px*/

.container {

/*prevent line breaks to maintain element alignment*/
white-space: nowrap;

overflow-x: scroll;  /*enable horizontal scroll*/
}
<div class="container">
  <div>
This content represents a child element
  </div>
</div>

As I cannot adjust the output window size here, I have created a jsFiddle demonstration for you to observe how it works live (just to be certain).

In the demo, I utilized a sample Lorem Ipsum text to simulate the overflow. Here, its exclusion prevents unnecessary scrolling within this response section.

Detailed Explanation of the Code

By implementing this code snippet, the scrollbar will become visible once the viewport width reaches 1200px. To trigger it precisely only above 1200px, adjust the media query to target 1201px.

Why Prefer CSS over JavaScript?

Using CSS eliminates any potential performance issues associated with JavaScript solutions handling scroll behaviors, particularly on extensive websites, resulting in improved overall performance.

Further Reading Resources

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to apply the text-shadow CSS property with the help of jQuery

I am attempting to utilize the text-shadow property by taking user-supplied values and updating it using JQuery. Below is my code: HTML Code <td width="13%"> H-Shadow::<input id="hshadow" onchange="setShadow();"/> </td> <td width="1 ...

The CSS component located just below the dropzone

I've encountered an issue with my infinite horizontal scrollbar. When I drag elements to the dropzone, they appear below it instead of above. Here's the HTML markup: <div class="wrapper"> <div class="header"> Drop here ...

Implementing a method for JQuery event handlers to access variables within a module pattern

var MODULE = (function() { var app = { hi: "hi dad", // How can I retrieve this value? onSubmitClick: function() { $('button').click(function() { console.log(hi); // Is there a way to access ...

Issue with Bootstrap4 Carousel not scrolling horizontally

I'm currently working on creating a carousel following the Bootstrap code snippet page. It features three images and is designed to have slide controls that move left and right. The script tags with the necessary scripts are located at the bottom of t ...

Using the Bootstrap 3 class visible-lg will cause the span to be placed on a separate line

Is there a way to prevent the class visible-lg from causing the span element to move to a new line? When using the following HTML code, the content displays on a single line: <p>Device is:<span>Unknown</span></p> However, when ut ...

Encase a group of child elements within a parent container using

Currently, I am able to wrap an entire li-element in an ordered list with a link: $(e).wrap('<a href="#" onclick="window.open(\'/xyz/\');return false;"></a>'); This is the HTML construct: <li class=""> ...

State changes not affecting the sorting of React elements

Whenever I update an array using react state, the value changes but the mapped react elements don't re-sort as expected. Here's the scenario: The initial state is [1, 3, 2], which is then mapped to another array and sorted to display [1, 4, 9]. H ...

Optimal method for implementing $scope.$apply(); or $scope in scenarios outside of Angular when working with Angular Components

As outlined in Kendo's best practices, there are instances where Kendo necessitates the use of $scope.$apply(); to update Angular. However, with the emergence of the new AngularJS 1.5 component, it is advised against relying on $scope. The code for t ...

What is the best way to create a sleek typewriter effect transition by hovering between tabs?

When hovering over a tab, the content in the main content area's child div should be displayed from a sibling div that holds the content. Initially, the details div style is set to hide the contents but upon hover, it is displayed. The described func ...

What is the best method for managing an event loop during nested or recursive calculations?

When it comes to breaking a computation and releasing using setTimeout(), most examples seen involve having a shallow call stack. But what about scenarios where the computation is deeply nested or mutually-recursive, like in a tree search, with plenty of c ...

Issue with Saving Query Loop Results in Prisma MySQL with NextJS/ReactJS

I'm struggling with a Prisma query that is giving me grief. Despite my best efforts, I can't figure out why it's not functioning properly. The getImages() method below is intended to retrieve all the images associated with a product. Query ...

What can be done to stop the event handler from executing?

My goal is to verify a user's authentication every time they click on a button. If the user happens to be logged out and tries to click on a button, they should be redirected back to the home page. The issue I'm facing is that the code after the ...

Transforming Angularjs into Vuejs

I am currently transitioning a chat application from AngularJS to VueJS, but I am facing some challenges as I am not very familiar with AngularJS. Unfortunately, there is a lack of comprehensive resources available for me to gain a better understanding of ...

Creating a unique custom shape for Bootstrap navigation bar

I'm looking to create a unique custom navigation bar shape inspired by the image attached below. https://i.sstatic.net/G7iIV.png To achieve this shape, I've utilized the following CSS: .navbar-nav.nav-bar-custom { transform: skew(-21deg); ...

Using AJAX in a loop iteration

I am struggling to grasp AJAX and its application for my specific needs. I am required to incorporate ajax calls within a foreach loop in my project. The challenge arises when contemplating the scenario where using PHP calls could result in all actions fir ...

Obtaining the current value with each keystroke

While working with vue.js, I'm building a table that contains an input field called quantity. However, when I start typing the first word, it shows 'empty' on the console. If I type 3, it displays empty; and if I type 44, it prints 4. I am ...

What is the method for defining field names in Highcharts?

Having experience with Kendo UI charts, I am new to highcharts. In Kendo, we could specify the fieldname for plotting the chart like this: series: [{ name: "steps", field: "steps", categoryField: "createddate" }] We could also define the data ...

Illuminate the current page

I have been working on a website with around 20 pages that all have a side navigation bar. To make it easier to manage, I decided to centralize the links in a JavaScript (JS) file and include it on each HTML page. This way, any changes can be made quickly ...

Exploring Node troubleshooting with WebPack and Feathers

Currently, I am part of a team working on a project that involves using Node, Webpack, TypeScript, and Express/Feathers. While my fellow developers are experienced in these technologies, I have limited experience with JavaScript mainly on the client-side a ...

Sending data to the server using AJAX with a Django form

I am currently working on implementing a system that allows users to upload both text and a file through my Django form. However, I have encountered an issue where only the message part of the form is being submitted when I try to post it. Even though I ha ...