Search code examples
javascripthtmlcssresponsive-designmedia-queries

JavaScript: Set scroll position variable according to media queries


I am working on a fade-in/out-effect-on-scroll on a web project. On my js I have to set a certain value for the scroll position i. e. the offset to make the effect kick in.

The problem:

  • The offset value cannot be applied to all kinds of devices due to different heights.

Questions (hierarchic):

  1. How to make the static values dynamic and variable to the device height/media queries?
  2. How can you generally slim down the code?
  3. How can I trigger an additional slide-slightly-from-right/left to the effect?

Here is the code:

    // ---### 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
    }
  });

Solution

  • See here for JavaScript Media Queries

    You can use window.matchMedia to perform media queries in JavaScript. Example:

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

    The result will be stored as a boolean in mediaQuery.matches, i.e.

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

    You can use multiple of these to suit your different device widths. Using the standard Bootstrap buckets:

    var sizes = ['1200px', '992px', '768px', '480px']; // standard Bootstrap breakpoints
    var fadeOutAs = [470, 500, 530, 560]; // this corresponds to your content a fadeout variable. Modify as required per screen size
    var fadeOutBs = [520, 530, 540, 550]; // content B fadeout
    var fadeOutCs = [1100, 1200, 1300, 1400]; // content C fadeout
    
    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];
        }
    }
    

    Hope this helps