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

Unable to apply the flex-grow property to a column flex box that has a specified minimum height

I am currently working on designing a website layout that harnesses the power of flexbox to fill the entire page with content, even when the content does not fully occupy the length of the page. My approach involves creating a large flexbox container with ...

Height not being applied to DIV container

I'm facing an issue with my CSS code that is causing images to break the row after reaching the end of the DIV. However, the container behind it is not adjusting its height according to the images. The height should expand along with the images. Here ...

Exploring CSS3 for Creating Stylish Navigation Bars

Currently, I am attempting to design a Navigation bar that resembles the style shown in this image, complete with a drop-down menu feature. Here is how I have structured my menu: <nav> <ul> <li> <a href="/i ...

What is the process for accessing my PayPal Sandbox account?

I'm having trouble logging into my SandBox Account since they updated the menu. The old steps mentioned in this post Can't login to paypal sandbox no longer seem to work. Could someone please provide me with detailed, step-by-step instructions o ...

The minmax() function is causing grid items to not wrap correctly

I have been working on creating a responsive web page where the "boxes" automatically adjust to a new row when the browser window is resized. To achieve this, I utilized the following CSS code: grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); ...

Directive containing tracking code script

I'm working on creating a directive to dynamically include tracking code scripts in my main page: <trackingcode trackingcodevalue="{{padCtrl.trackingnumber}}"></trackingcode> This is the directive I have set up: (function () { 'use ...

The responsiveness of Slick Slider's breakpoints is malfunctioning

After implementing a slider using slick slider, I encountered an issue with the width when testing it online and in a normal HTML file. If anyone could assist me in resolving this issue, I would greatly appreciate it. Please inspect the code for both scen ...

Can a websocket be used to communicate with a server that is not the same as the one hosting the html5 website?

My goal is to establish communication between a hardware device and an HTML5 website. It seems like the best way to do this would be through WebSockets or possibly WebRTC over a WiFi network. Is that correct? I haven't come across any solutions invol ...

Hide multiple divs with similar ids in JQuery when clicking outside of them

Is there a way to hide all div elements with similar id if none of them are clicked on? Currently, my code only works for the first div because I am using index[0] to retrieve the id. How can I make it work for all ids? Below is the code snippet: $(win ...

What is the best way to organize a table with multiple state variables using nested loops?

What is the best way to display multiple variables in a table using a loop, such as i,j,k? this.state = { materials: ['m1', 'm2'], quantity: ['2', '4'], unitPrice : ['12&apo ...

position the tooltip within the ample available space of a container in an angular environment

In my editor, users can create a banner and freely drag elements within it. Each element has a tooltip that should appear on hover, positioned on the side of the element with the most space (top, left, bottom, right). The tooltip should never extend outsid ...

This is my first experience with Flask and I am encountering an issue with the POST method

Recently, I began my journey of learning Flask and encountered a seemingly simple task: creating a button, capturing the name, and displaying it on the screen. Despite my efforts, the code doesn't seem to be working as expected. It's now been two ...

The React Native application continuously crashes following the installation of react-native-gesture-handler

I recently embarked on building an app using React Native 0.60. The initial build worked smoothly, but after installing and setting up react-native-gesture-handler, my app started crashing in the emulator. There were no error messages, it just kept crashin ...

The scroll animation feature was not functioning properly in Next.js, however, it was working flawlessly in create react app

I recently transitioned a small project from Create React App (CRA) to Next.js. Everything is working as expected except for the scroll animations in Next.js, which are not functioning properly. There are no errors thrown; the animations simply do not occ ...

Why isn't Sequence.js Slider automatically playing?

Issue: The sequence.js slider I implemented is not animating. Despite adding the following options: animateCanvas: true, fadeStepWhenSkipped: false, autoPlay: true, autoPlayInterval, 2000 It still does not work. Is there something essential t ...

refetchQueries may be effective for specific queries

Using a Friend component within my AllFriends screen triggers the following mutation: const [deleteUserRelation] = useDeleteUserRelationMutation({ onCompleted: () => { Alert.alert('Unfriended'); }, refetchQueries: [{ query: ...

What steps should I take to establish an efficient folder organization system for a website utilizing HTML, CSS, and Javascript with Twitter Bootstrap?

After cloning the latest release of Twitter Bootstrap using Git with the command 'git clone git://github.com/twbs/bootstrap.git', I am in the process of creating an HTML/CSS site utilizing Bootstrap. Upon reviewing this answer on Stack Overflow ( ...

Steps for showcasing a automated slideshow

I'm currently working on creating a slideshow that automatically displays multiple images. While the first image shows up just fine, it doesn't seem to transition to the next one. var currentSlide = 0; displaySlides(); functio ...

Developing various themes using Material UI in React for multiple pages

I have a variety of pages, each with its own unique theme or color scheme. What is the best approach for managing this in React with Material UI? I initially tried using CustomThemeProvider following this guide: However, I encountered issues where the pr ...

How to Utilize Raw HTML in GWT with the Power of Jquery/Javascript?

Below is the HTML code snippet: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function( ...