Tips for activating a sticky navigation button by scrolling down slightly

Currently in the process of developing a website using React and focusing on optimizing the mobile version first. One feature I am working on is to have a sticky navigation bar that remains at the top after scrolling down. In the attached picture, there is also a button located on the right side. I would like this button to transition with the sticky navigation bar as users scroll down - initially it appears at the top, then moves along with the navigation once the user starts scrolling.

I am coding this website with React. Could someone provide guidance on how to achieve this effect?

Image link: https://i.stack.imgur.com/TiqBv.png

Answer №1

If you want to achieve this effect, you can include some JavaScript in your code.

const scrollButton = document.querySelector(".scroll");
document.addEventListener('scroll', handleScroll);
function handleScroll(){
    scrollButton.style.display = 'block';
}
.scroll{
    display: none;
}
<html>
<body>
<button class = "scroll">Scroller</button>
</body>
</html>

Answer №2

To ensure there is no memory leak, when adding an event listener for scroll, it is recommended to utilize either componentDidMmount and componentWillUnmount, or the useEffect hook.

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        
        this.state = {
            showButton: false
        }
    }
    
    handleScroll(e) {
        const y = window.pageYOffset || document.documentElement.scrollTop;

        if (y > 80) {
            this.setState({showButton: true});
        } else {
            this.setState({showButton: false});
        }
    };
    
    componentDidMount() {
        window.addEventListener('scroll', this.handleScroll.bind(this));
    }
    
    componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll.bind(this));
    }

    render() {
        return (
            <div className="body">
                <div className="fixed-header">
                    <button className={this.state.showButton ? 'show' : 'hide'}>Can you see me?</button>
                </div>
            </div>
        );
    }
}

ReactDOM.render(<MyComponent />, document.getElementById('root'));
.show {
    display: block;
}
.hide {
    display: none;
}
.body {
    height: 500px;
}
.fixed-header {
    position: fixed;
    top: 0;
    left: 0
    width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Answer №3

Check out this example

window.addEventListener('scroll', function(e) {
console.log('Scroll', window.pageYOffset)

I am using a window scroll listener to monitor the scroll position. By placing the Signup button along with the navigation, I am creating a specific scrolling behavior after reaching a certain offset. Through a script, I detect the scroll position and determine whether to keep the button in the header or move it inside the nav based on the scroll limit.

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 is the best approach for integrating Stripe with React and Django Rest - in the frontend or backend?

I'm feeling a bit perplexed as I've come across two different solutions after a full day of researching. Some are recommending to use "pip install dj-stripe" and include keys and other options in "settings.py". Then using a script in the fronten ...

Utilizing React JS: Displaying or Concealing Specific Components Based on the URL Path

Is there a way to dynamically change the navbar items based on the URL without having separate navbar components for each side? My current navbar design features 3 links on the left side and 3 links on the right, but I want to display only one side at a ti ...

Tips for implementing defaultValue within the select tag on a functional component

I am working on a functional component that includes a select tag with various options. My goal is to have "cars" as the default value for the select tag. Initially, I tried adding selected to the car's option but React warned me to use defaultVa ...

ReactJS cannot retrieve the API data

I need help with my to-do list application. Whenever I try to pass data from an API as a prop, I encounter the error message: TypeError: Cannot read property 'length' of undefined. How can I ensure that my data is successfully fetched before pass ...

How to Handle the Absence of HTML5 Spellcheck in Specific Web Browsers

While HTML5 spellcheck functionality may vary across different browsers, there are instances where it might not be supported in certain corporate environments. In the event that HTML5 is not supported in a particular browser, it's essential to first c ...

Unable to generate the react app due to the discovery of a single low-severity vulnerability

When attempting to create an app using the command **npx create-react-app my-app** in the terminal, I encountered a problem. The CMD froze and nothing happened even after waiting for over 30 minutes. Only the node modules, package.json, and package.lock.j ...

"What is the most effective way to utilize and integrate the `setValue` function from react-hook-form within a custom react hook

Struggling to pass setValue to a react hook? In my custom react hook, I need to set values in a form using react-hook-form's setValue. Yet, after migrating from v6 to v7, I'm having trouble figuring out the proper typing for this. This is how t ...

How to adjust the background picture opacity in HTML

Is it possible to adjust the transparency of a background image in HTML? I came across one solution that involved adding a box on top of the background picture and changing the opacity of the box, which in turn changed the opacity of the background pictur ...

Set the first link in a menu to be highlighted as active using jquery

In order to mark the first link in my menu as active, I need it to have specific CSS settings applied. Using jQuery to add these settings to every link when clicked on makes it a bit tricky (simple menu = clicking changes color). So, I want the first link ...

The execution of the selenium script is unreliable

Recently, I created a selenium script to automate certain manual checks on http:obsessory.com. The script utilizes a looping concept, such as mouse hovering over the Top menu and clicking on various submenus. However, during testing, I have encountered spo ...

Establishing a parameter in the main component

In my current project utilizing react-router and redux, I have the below App component: export default class App extends Component { render() { return ( <div> <Header /> <PageTitle title="Projec ...

Avoid page refreshing when modifying app.js in React

Today is only my second day using React and I started by creating a React app with "npx create-react-app." However, when I tried to make changes to the app.js file, they didn't appear on the page even after refreshing the browser multiple times. (My n ...

Error: Module not found - Issue with importing SVG files in NextJS

Currently, I am utilizing the babel plugin inline-react-svg to import inline SVGs in NextJS. Here is a snippet from my .babelrc configuration file: { "presets": ["next/babel"], "plugins": [ "inline-react-svg" ...

Tips for inserting a php variable into an html document

I am trying to figure out how to export a variable from a php file into an html file. The php file I'm working with is example.php and it contains the following code: <?php $array= ['one','two']; ?> The html file is named ...

Rotate images every 5 seconds, pulling them directly from the server

I am looking to update the users every seven seconds on my website. To do this, I need to retrieve all user information from the server using JavaScript. What is the most efficient way to accomplish this task? My initial thought is to send an HTTP request ...

Using JQuery and Ajax, what is the best way to transfer information from a popup form to a PHP page?

I've noticed that my question has been asked a few times already, but I'm still struggling to get my code working. It seems like I'm using the same code as those solutions, so I can't figure out what's going wrong. Currently, I am ...

retrieve the data attribute of a link within an unordered list

I have been attempting to extract a data attribute from a link within a list when it is clicked on. $(document).on('click', "ul.pagination li a", function(e) { e.preventDefault(); var page = $(this).attr("page"); var article_id = get ...

Make sure to consistently receive the distinct key notice: Every child within a set must possess a unique "key" property

Trying to understand the part of this code that suggests I don't have keys for the pushed array items: import { Accordion, AccordionSummary } from '@material-ui/core' import { createStyles, makeStyles, Theme } from '@material-ui ...

Whenever I attempt to send a message in React, it keeps displaying the same message repeatedly

https://i.stack.imgur.com/UBkMK.png The image above illustrates the issue at hand. You can also check the console in the bottom right corner for more details. I am currently working on a one-to-one chat website using Socket.io with React, Node.js, and Exp ...

arranging the divs based on the space allocation within the page

Is there a way to neatly organize the divs on a page, depending on available space? I want them to align horizontally if there is enough room before moving to the next line. The tab-content parent div may contain several divs. Any suggestions on how this c ...