Is it possible to achieve consistent scrollY height values across various screen sizes?

Looking to apply a class when a certain screen height is reached? Here's my approach:

window.onscroll = function() {scrollPost()};

function scrollPost () {
    var x = window.screen.width;
    var i = window.scrollY;
    var a = i / x;
    animator (a);
    slide(a);
}


function slide(x){

var a = (x * 100);
var i = Math.round(a);
console.log(i);
var slideIn = document.querySelector(".slide-in-right");
var slideOut = document.querySelector(".slide-out-left");

if (i >= 90){
slideOut.classList.add("animate");

slideIn.classList.add("animate");
slideIn.style.display = ("block");
    }

The issue I'm facing is that the toggle time varies on different screens due to different values. Adding multiple if statements based on screen width seems like an option, but could lead to a lot of clutter.

To solve this, I want the animation to trigger only when the container reaches 100% of the screen height. Any suggestions on how to achieve this?

Answer №1

  • To get the user's viewport (window height), simply divide it by half and add it to your IF position.
  • If you prefer jQuery, I had a similar answer written in that language which may provide a better output.

If you are interested in triggering a class that is only in view using waypoints, you can check out this helpful link: How to trigger a class that is only in view with wapoints

If you want to implement the solution in plain JavaScript:

First, get the user's screen height:

var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementsByTagName('body')[0],
    x = w.innerWidth || e.clientWidth || g.clientWidth,
    y = w.innerHeight|| e.clientHeight|| g.clientHeight;
alert(x + ' × ' + y);

Next, divide y by half, and then add it to your current position check for scrolled elements.

Here's a function to help you get the position of an element:

function getPosition(element) {
    var xPosition = 0;
    var yPosition = 0;

    while(element) {
        xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
        yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
        element = element.offsetParent;
    }

    return { x: xPosition, y: yPosition };
}

For more information on getting the distance from the top for an element, you can visit: How to get the distance from the top for an element?

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

What steps are involved in creating a default toolbar for a material picker in a React application?

Looking for assistance with customizing the toolbar for material picker (v3) by adding a title inside the dialog. I successfully implemented this in the KeyboardDatePicker following a helpful thread (https://github.com/mui-org/material-ui-pickers/issues/11 ...

Displaying and Concealing Divisions

My journey to showing/hiding divs began with piecing together a series of questions: $(document).ready(function(){ $('.box').hide(); $('#categories').onMouseOver(function() { $('.box').hide(); $('#div' + ...

Issue with Website Rendering: Safari 4 exhibits display glitch showing temporary content before showing a blank white screen

Currently, I'm in the process of developing a specialized rails application. However, there seems to be an unusual rendering error that has been reported by Safari 4 users. It's quite peculiar because the page appears briefly but quickly disappea ...

Discover the method for accessing a CSS Variable declared within the `:root` selector from within a nested React functional component

Motivation My main aim is to establish CSS as the primary source for color definitions. I am hesitant to duplicate these values into JavaScript variables as it would require updating code in two separate locations if any changes were made to a specific co ...

JavaScript Audio working on local machine but not on server due to HTML5 compatibility issues

For my project, I am utilizing audio and Javascript in the following way: To start, I populate an array with audio files: var soundArray = new Array(); for (i=0; i<6; i++) { soundArray[i] = new Audio('sounds/sound_' + i + audioExt); ...

How to Make a Zigzag Formation in three.js?

I have been working on developing a 3D tool and was in need of a zigzag structure. I managed to create it by iterating a function that produces 'V' multiple times, but now I am looking for a way to achieve the same effect using a single geometry ...

How to dynamically change the class of an element that contains other elements using JavaScript and JQuery

I have created a blog archive with the following format: +Year +Month Title Here is a snippet of the code: <ul> <span class="toggle">+</span> <li class="year">$year <ul> <span ...

Bookeo API allows only a maximum of 5 requests to be processed through Node.js

Greetings! I am excited to be posting my first question here, although I apologize in advance if anything appears unclear! My current project involves utilizing Bookeo's API to extract booking data from emails belonging to a tour company and transfer ...

Connect radio input's value to object's key within AngularJS

Within my controller, I currently have an object structured as follows: $scope.colors = { green: "Green", yellow: "Yellow", red: "Red" }; I am attempting to dynamically generate radio inputs and then link the input value to the corresponding ...

React Jodit Editor experiencing focus loss with onchange event and useMemo functionality not functioning properly

I'm currently working on a component that includes a form with various inputs and a text editor, specifically Jodit. One issue I've encountered is that when there are changes in the Jodit editor's content, I need to retrieve the new HTML va ...

Why are the $refs always empty or undefined within Vue components?

I am completely new to working with Vue and I've been attempting to utilize $refs to retrieve some elements within the DOM from a sibling component. My objective is very basic, as I just need to obtain their heights, but I haven't had much succes ...

The Shopify storefront API's create cart mutation generates an HTML response when called

I recently started developing an e-commerce website using Next.js and Shopify's storefront API. I have successfully set up the connection and can list all the products from the API. However, I encountered an issue when attempting to add a product for ...

Do the dependencies in the devDependencies section impact the overall size of the

My search for a definitive answer to this question was fruitless. Are the packages I include as devDependencies included in the final production JS bundle, impacting its size? Or does only the dependencies list affect the bundle's content? ...

Displaying genuine HTML content in a React application using Algolia Instantsearch

After setting up a demo app using React with an Algolia search feature, I uploaded some indices into Algolia. The content consists of raw HTML. Is there a way to display this content as real HTML using Algolia? ...

GET method returns an empty array in the express node server

app.get('/:user/:tag', function (req, res) { fs.readdir( 'api'+path.sep+req.params.user, function (err, files) { var tweets=[]; for (var i =1, j=files.length ; i <j; i++) { fs.readFile('api'+path.sep+ ...

Effective ways to transmit a variable array from an HTML document to a PHP server

Is there a better method for transferring a variable array from HTML to PHP? I attempted to use the serialize function, but it doesn't seem to be functioning correctly. Any suggestions would be greatly appreciated. //HTML var arrayTextAreasNames = [ ...

Incorporating a new parameter into the JSON response from SoundCloud

Currently, I am in the process of developing an app utilizing the SoundCloud JavaScript API. My approach involves fetching the JSON data from: http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/matas/hobnotropic&client_id=YOUR_CLIENT_ID ...

The Autocomplete component from MUI is alerting me to provide a unique key for every child element being passed

I am currently using the Autocomplete component from MUI and encountering an issue with a warning that says: Warning: Each child in a list should have a unique "key" prop. Although I've added keys to both renderOption and renderTags, the wa ...

What is the best way to iterate through a JSON file?

Looking at my JSON file: { "stats": { "operators": { "recruit1": { "won": 100, "lost": 50, "timePlayed": 1000 }, "recruit2": { "won": 200, ...

The canvas element automatically removes itself after being resized within an HTML5/JavaScript environment

I created a canvas that is interactive and responsive to screen size. However, I encountered an issue where the canvas clears itself when the browser is resized by just one pixel. Is there a way to prevent this from happening? I have included code in my sc ...