Managing scroll position based on media queries in JavaScript

I'm currently working on implementing a fade-in/out effect on scroll for a web project. In my JavaScript code, I need to specify a certain value for the scroll position, such as an offset, to trigger the effect.

The issue:

  • The offset value may not work well on all types of devices with different screen heights.

Key Questions:

  1. How can I make the static values adaptable and responsive to the device's height using media queries?
  2. How can I optimize the code to make it more compact?
  3. Is there a way to incorporate a slight slide effect from the right/left in addition to the existing fade effect?

Below is the code snippet:

    // ---### FOUNDATION FRAMEWORK ###---
$(document).foundation() 

// ---### FADE FX ###---  

// ## SECTION-01: fade out on scroll ##  
$(window).scroll(function(){  
    // fade out content a  
    $(".j-fadeOut").css("opacity", 1 - $(window).scrollTop() / 470);// 470 should be variable  

    // ## SECTION-02: fade in/out on scroll bottom ##  
    var offset = $('.j-fadeOut-2').offset().top;  
    console.log('offset: '+offset);  
    console.log('window: '+$(window).scrollTop())
    if($(window).scrollTop() > offset)  
    {  
      // fade out top part of content b  
        $(".j-fadeOut-2").css("opacity", 1-($(window).scrollTop() - offset)/520);// 520 should be variable

      // fade in bottom part of content c
      $(".j-fadeIn").css("opacity", 0 + ($(window).scrollTop() - offset)/ 1100);// 1100 should be variable
    }
  });

Answer №1

Check out this guide on JavaScript Media Queries

When working with JavaScript, you can utilize window.matchMedia to handle media queries. For instance:

var mediaQuery = window.matchMedia("(min-width: 800px)");

The outcome will be saved as a boolean in mediaQuery.matches, indicating whether the condition is met or not.

if (mediaQuery.matches) {
  // Window width is at least 800px
} else {
  // Window width is less than 800px
}

You can implement multiple queries to accommodate various device widths. For instance, utilizing the typical Bootstrap breakpoints:

var sizes = ['1200px', '992px', '768px', '480px']; // Standard Bootstrap breakpoints
var fadeOutAs = [470, 500, 530, 560]; // Corresponding fadeout values for content A, adjust according to screen size
var fadeOutBs = [520, 530, 540, 550]; // Fadeout values for content B
var fadeOutCs = [1100, 1200, 1300, 1400]; // Fadeout values for content C

var fadeOutA = 0;
var fadeOutB = 0;
var fadeOutC = 0;

for (i = 0; i < sizes.length; i++) {
    var mediaQuery = window.matchMedia("(min-width: " + sizes[i] + ")");
    if (mediaQuery.matches) {
        fadeOutA = fadeOutAs[i];
        fadeOutB = fadeOutBs[i];
        fadeOutC = fadeOutCs[i];
    }
}

I hope this explanation proves useful for your needs.

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

Animating colors with jQuery and shifting SVG shapes to create dynamic and

I am currently working on an svg animation that involves changing the color of the svg to a different color, creating a running light effect. Rather than fading the fill color of the entire svg as commonly seen in examples, I aim to achieve a dynamic trans ...

processing an array using ajax form submission

Trying to manage an array that is returned from a PHP file after submitting form data. The value of the data after form submission is = ARRAY but I am unable to use this array in any way. Any suggestions on how to handle this array? Javascript: $(&apo ...

Is it possible to rotate just the camera in ThreeJS by dragging the mouse within the scene?

Currently, I am involved in a project using ThreeJS and I am looking to implement camera rotation using the mouse. Although I have come across OrbitControls that allow me to rotate the camera around a point or object, I am unable to achieve the camera rota ...

Having trouble aligning page in the center with flexbox and styled components

Hey there, I'm having some trouble figuring out how to center my page using flexbox within styled components in a Next.js app. Any suggestions or tips? Let me share with you my Blog Component import ReactMarkdown from 'react-markdown' impor ...

Adjusting icons based on the length of the text

When I have a title text and an icon, I want to align the icon to the left if the title fits on a single line. However, if the title spans multiple lines, then I need to align the icon to the top. I recently discovered a solution that involves using Javas ...

Retrieving the background image URL from inline CSS using jQuery

I'm looking for a link similar to url(img/bg/06.jpg), but when using jQuery, I get a longer link like url("file:///D:/WORKING%20FILE/One%20Landing%20Page/version/img/bg/06.jpg") https://i.stack.imgur.com/8WKgv.png Below is the code snippet in questi ...

Retrieve data from a JSON object and assign it to a variable in JavaScript

I'm currently working on implementing AJAX to send and receive data in Django. My model consists of three fields: id, parent, and text. However, when attempting to post the information back to Django, I encounter an error due to additional fields pre ...

Retrieving the nth character from a given string

How can I extract every 3rd character from a given string, such as the word GOOGLE? I have attempted to accomplish this using JavaScript, but I am unsure of what code to include after the 'if' statement. function getNthElements(string) { v ...

code snippet showing HTML element's visibility

I have a component in my HTML that I need to hide: <div class="hid" > <select > <option value="M">Male</option> <option value="F">Female</option> </select> </div> To hide the component, I added ...

Using the Vue.js Compositions API to handle multiple API requests with a promise when the component is mounted

I have a task that requires me to make requests to 4 different places in the onmounted function using the composition api. I want to send these requests simultaneously with promises for better performance. Can anyone guide me on how to achieve this effic ...

Show the JSON response from the controller on the view page

In my controller, I have a JsonResult action that returns a list of House objects. My goal is to retrieve this data onclick using ajax and display the JSON data within my view. While I can see the proper response and JSON result in Firebug, I'm not su ...

Encountering path import errors when developing a sample webpack site within a TypeScript library

Struggling to integrate my custom library with TypeScript and Webpack. Import errors are causing headaches, despite smooth sailing in CLion. Running tsc within the project directory is error-free, unlike when running npm run dev in the examples/webpack di ...

When I click on my div, the color does not change as expected

Recently, I wrote a code snippet where there are 9 different div elements each assigned a ".spaces" class. The intention was to change the color of these divs upon clicking on them. However, I encountered an issue where only the first div changes its color ...

Utilizing a font URL imported through a script

I am currently working on incorporating the pdfmake package into my application. In order to load fonts, a list of URLs is required during initialization. However, the fonts I am using are managed by npm and Vite, so they do not have fixed URLs. Here' ...

What is causing vertical-align:middle to not function in the same way as text-align:center?

Is there a reason why vertical-align:middle doesn't seem to work as easily as text-align:center? It's frustrating that it's so challenging to get it right. I'm curious why the folks at W3C haven't created something like text-alig ...

How to retrieve values from dynamically generated text boxes using ng-repeat in AngularJS

When using ng-repeat, I am able to display textboxes related to each item. Upon clicking the SaveAll button, I intend to retrieve all textbox values based on ITEM ID and save them to the database. <tr> <td> <table ng-repeat="item in ...

What is the best way to include multiple tags (specifically for articles) in the Facebook Open Graph?

When it comes to a single blog or article with multiple tags, how can you add Facebook Open Graph data? This method seems like the most logical way to do it. However, the Facebook debugger reports that it's incorrect: <meta property = "article: ...

Issues with CSS causing image resizing problems on Chrome, looking for solutions

On my website, I have favicons from various external domains. However, there seems to be an issue with resizing them when they are not 16px in size. Sometimes only the top or bottom half of the image is displayed, but upon refreshing the page, the entire i ...

The RSS feed reader is currently malfunctioning

I'm having trouble loading an RSS feed from the following URL: http://solutions.astrology.com/scripts/it.dll?cust_id=aamfha&doc=daily07short/dailyshort.xml Here is the code I am using to try to read it: url = 'http://solutions.astrology.co ...

Incorporating traditional Javascript classes for modeling in React development

Can traditional JavaScript classes be utilized in models within the MVC framework while using React, as opposed to relying on Redux or contexts & reducers which may impact reusability? If this approach is feasible, how can we efficiently 'subscribe&ap ...