How can I trigger scroll events after the screen has reached a certain point or JSX tag?

I'm facing a challenge that seems simple, but I can't seem to find the solution. How can I trigger a scroll event once a certain point on the page has been scrolled past?

Just to clarify, I already know how to handle scroll events; my specific question is about triggering events at specific "scroll points."

In essence, I want to implement a functionality where certain words fade in when scrolled past specific points on the page.

Below is a snippet of code where I've attempted to address this:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

class Nav extends Component {
    state = {
        background: "",
        backgroundImage: "linear-gradient(to bottom right, white, white",
        navSize: "83px"
    }
    
    componentDidMount() {
        window.addEventListener('scroll', this.handleScroll);    
    } 
    
    componentWillUnmount() {
         window.removeEventListener('scroll', this.handleScroll);
    }
    
    handleScroll = () => {
        let currentPosition = 0;        
        currentPosition = (document.body.getBoundingClientRect()).top;
        
        console.log(currentPosition);
        
        if(currentPosition === 116) {
            this.setState({navSize: "130px"})
        } else {         
            this.setState({navSize: "100px"})
        };
    }
    
    render() {
        const { backgroundImage, navSize } = this.state;                
        
        return(
            <div style={{ backgroundImage }} className="nav-root">
                <div style={{ height: navSize }} className="nav-inner-wrapper">
                    <div className="nav-normal">
                        <h3 className="font-size-increase0" >RandomText + The Triangular = RandomText</h3>                                                      
                    </div>
                </div>
            </div>
        )
    }
}

Nav.propTypes = {
    user: PropTypes.shape({
        email: PropTypes.string
    }),
    logout: PropTypes.func
};

Nav.contextTypes= {
    router: PropTypes.object.isRequired
}

export default connect(null, {})(Nav);

Answer №1

Check window.pageYOffset to monitor the user's scrolling progress:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

class Navigation extends Component {
    state = {
        background: "",
        backgroundImage: "linear-gradient(to bottom right, white, white",
        navSize: "83px"
    }
    componentDidMount() {
        window.addEventListener('scroll', this.handleScroll);    
    } 
    componentWillUnmount() {
         window.removeEventListener('scroll', this.handleScroll);
    }
    handleScroll = () => {
      const doc = document.documentElement;
      const scrolledAmount = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
      if (scrolledAmount === 116) {
        this.setState({navSize: "130px"})
      } else {         
        this.setState({navSize: "100px"})
      }
    }
    render() {
const { backgroundImage, navSize } = this.state;                
        return(
        <div style={{ backgroundImage }} className="nav-root">
                    <div style={{ height: navSize }} className="nav-inner-wrapper">
                        <div className="nav-normal">
                            <h3 className="font-size-increase0" >RandomText + The Triangular = RandomText</h3>                                                      
                        </div>
                    </div>
                </div>
            )
    }
}

Navigation.propTypes = {
    user: PropTypes.shape({
        email: PropTypes.string
    }),
    logout: PropTypes.func
};

Navigation.contextTypes= {
    router: PropTypes.object.isRequired
}

export default connect(null, {})(Navigation);

Answer №2

In my view, employing modules is the way to go for creating clean code.

Whenever I develop websites or applications, I rely on this

I am confident that you will enjoy using it~!

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

Transforming a callback function into a Promise: A step-by-step guide

I'm currently utilizing Bluebird promises and attempting to make the following function work with Promisify: var jwt = require('jsonwebtoken'); function _test_encode() { var cert = fs.readFileSync('public.pub'); return j ...

Ways to incorporate input with redux

Seeking assistance with creating a todo-app using redux. Struggling to render input data and unable to create items when clicking the button. Any guidance on utilizing input with redux would be greatly appreciated. Visit the project here. Thank you! import ...

Caught off guard by this promise: TypeError - Attempting to access a property that does not exist in my Ionic 2 application

I'm encountering an issue with native Facebook login that displays the following error message: Uncaught (in promise): TypeError: Cannot read property 'apply' of undefined https://i.sstatic.net/PDWze.jpg I have shared my entire project ...

CSS - Struggles with Keeping Div Positioned to the Right of Another

I'm facing a simple layout issue here - trying to align two divs next to each other. Image on the left, text on the right. However, when the text is too long, it pushes the div down instead of wrapping around. I want the cs-summary div to automaticall ...

Switch out the content when the button is clicked

Seeking a code snippet to enable clicking a button (Button labeled "Next") for replacing existing code on the page with new code. Current code below should be replaced, starting from the score counter section. Please excuse any messy code as I'm new a ...

How can I update a specific element within an array of objects in JavaScript based on its reference rather than its index position?

I am dealing with multiple arrays of objects x=[ {a:1}, {b:2}, {c:3}, {d:4} ] y=[ {e:5}, {f:6}, {g:7}, {h:8} ] (etc) and I have a list of references pointing to the objects I need to replace. Instead of having an index into the array, I hold reference ...

The number input component that is meant to be reusable is experiencing functionality issues within the NUXT framework

I have a reusable input component that is being used in various places. Everything works well with the number input, but the issue arises when I completely clear the input. This action triggers a warning message in the console: [Vue warn]: Invalid prop: t ...

Angular animation will be triggered when the user clicks using ng-click

In my Angular project, I'm looking to implement an animation that will enlarge the size of an image. Below is the code snippet: <div class="card"> <div class="item images-parent"> <img src="img/carryout-icon.jpg" class="left-image" ...

Authentication using HttpOnly cookies

export const login = (credentials) => async (dispatch) => { try { const { data } = await axios.post("/auth/login", credentials); dispatch(gotUser(data)); socket.emit("go-online", data.id); } catch (error) { console.error(error); ...

What's the reason for the align-self: flex-end CSS property not working as expected on a flex div element?

I am trying to align the "Click me" button to the left of the div that contains it. Here is my code: render = () => { return ( <Wrapper> <Body> <span>Title</span> <Desc ...

Position the div in the center, but for smaller sizes, switch to aligning

My current layout setup is as follows: Left side bar with a width of 200px and positioned at left: 0; Center section with a width of 700px and positioned at left: 250px; Right side bar with a width of 200px and positioned at right: 10px; While this arra ...

Is there a Ruby solution for converting external CSS to inline CSS?

Exploring GoogleDocs, I noticed that it has limited CSS support. When uploading an MSWord .doc or HTML file and exporting it as HTML, all styles are applied inline. Although there is a style block in the HTML file, non-inline styles do not get applied when ...

Updating Data with Ajax in Laravel

Hey there, could you walk me through the process of updating with Ajax? I'm working with Laravel I prefer using HTML and Ajax only Here are my routes: Route::post('/post/homepage', 'AdminController@HomePage'); ...

Discovering the selected option's value in a dropdown and utilizing it to search through an array for data to fill another input

Is there a way to utilize the value of a select input option, created by a forEach loop, to extract the value of another property in the same array object and assign it as the value of a different input field? Apologies if this seems verbose or has been a ...

Function activation in Element requires a double click to initiate

I've encountered an issue with a web element I'm working on where the click function only triggers after the first click, rendering the initial click ineffective. Here's the code snippet in question: HTML: <div> <a href="#0" cla ...

The div element on the HTML page is not displaying all of its content

I've created the following code snippet on JSFiddle. https://jsfiddle.net/msridhar/1zvhmpjq/11/ HTML file: <body> <div id="headerDiv"> <img id="headerImg" src="" width="280" height="125" alt="DummyLogo"/> <pre id ...

Determine in JavaScript whether a character is 32-bit or not

Is there a way to determine if a specific character is 32 bits using JavaScript? I attempted to use charCodeAt() but it was unsuccessful for identifying 32-bit characters. Any guidance or assistance on this matter would be greatly valued. ...

Enhancing nested mongoose arrays by a particular value for updates

In my mongoose schema, I have an array that contains items and another array. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var CompanySchema = new Schema({ dateCreated: { type: Date, default: Date.now }, ownerId: { typ ...

ui-select: expected a certain input, but instead received a period (.)

After updating to the latest angular-ui-select version 0.12 with angular v1.2.27, my webpage is refusing to load and displaying the error message: expected expression, got . (a point) This error seems to be linked to the following section in my vendor.js ...

Fixing SCRIPT1028 error in IE9 with the help of AngularJS

Utilizing AngularJS in my single-page application, I have a button defined as follows: <button class="btn btn-success" onclick="doSeekTo({{todo.position}});doPlay();"> When this button is clicked, it triggers the javascript function with the specif ...