What could be causing my sticky positioning to not function properly when I scroll outside of the designated

My website is organized into sections, with each section corresponding to a hyperlink in the navigation menu. I've applied the CSS property position: sticky to my navbar, which works as expected within the section bounds. However, I want my red navbar to remain visible not only in the yellow section, but across all sections of the website - yellow, green, or blue.

$('.links a[href^="#"]').click(function (event) {
  event.preventDefault();
  const section = document.querySelector(event.target.getAttribute("href"));
  section.scrollIntoView({
    behavior: "smooth"
  });
})

$(document).scroll(function () { 
  $("nav").toggleClass("sticky", window.scrollY > 0);
});
body{
    margin: 0;
    box-sizing: border-box;

}


nav.sticky{
    background-color: blue;
    border-bottom: 10px solid black;
}

nav img{
    width: 10vh;
}

nav.title-bar{
    background-color: red;
    display: block;
    position: sticky;
    top: 0;
    width: 100%;
    transition: 0.5s;
    height: 50vh;
    z-index: 10000;
    color: white;


    nav.title-bar > *{
        padding: 20vh;
    }

}

#first{
    background-color: yellow;
}

#second{
    background-color: green;
}

#third{
    background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <section id="first">

        <nav class="title-bar">
            <div class="logo">
                <img src="https://picsum.photos/200" alt="logo" id="logo">
                <h1 id="title"><a href=".">My Website</a></h1>
            </div>

                <div class="links">
                    <a href="#first" class="selected">First</a>
                    <a href="#second">Second</a></label>
                    <a href="#third">Third</a></label>
                </div>
        </nav>

        <div class="div-1">
            <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Vel mollitia tempora labore, ad laboriosam modi recusandae ipsam tempore quasi tenetur, veritatis, alias pariatur qui doloremque accusamus temporibus doloribus porro aperiam?</p>
            <img src="https://picsum.photos/200/300">
            <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. At maiores sunt voluptatum quas laboriosam, ducimus nesciunt ipsa quis, ullam rerum ipsam consectetur aperiam, mollitia totam aliquid sit exercitationem eius facilis?</p>
            <img src="https://picsum.photos/200/301">
        </div>

    </section>

    <section id="second">
        <div class="div-2">
            <img src="https://picsum.photos/200/302">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum quod, mollitia cumque quisquam itaque earum vel voluptatibus nesciunt quas provident inventore doloribus amet est possimus, consectetur maxime consequatur. Delectus, corporis?</p>
        </div>

        <div class="div-3">
            <img src="https://picsum.photos/200/303">
            <ul>
                <li>aaaa</li>
                <li>bbbb</li>
                <li>cccc</li>
                <li>dddd</li>
            </ul>
        </div>
    </section>
    
    
        <section id="third">
        <div class="div-2">
            <img src="https://picsum.photos/200/302">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum quod, mollitia cumque quisquam itaque earum vel voluptatibus nesciunt quas provident inventore doloribus amet est possimus, consectetur maxime consequatur. Delectus, corporis?</p>
        </div>

        <div class="div-3">
            <img src="https://picsum.photos/200/303">
            <ul>
                <li>aaaa</li>
                <li>bbbb</li>
                <li>cccc</li>
                <li>dddd</li>
            </ul>
        </div>
    </section>
</body>
</html>

Answer №1

According to MDN Web Docs:

Keep in mind that a sticky element will adhere to the closest ancestor with a scrolling mechanism (such as overflow hidden, scroll, auto, or overlay), even if that ancestor isn't actually the closest scrolling ancestor. [1]

Your <nav class="title-class> will stay fixed to the nearest scrolling ancestor, which is . Therefore, your navbar will always remain within its container.

Solution:

Position the navbar as the first child of the body element.

Answer №2

Here's a simple solution, just adjust the position of the links

$('.links a[href^="#"]').click(function (event) {
  event.preventDefault();
  const targetSection = document.querySelector(event.target.getAttribute("href"));
  targetSection.scrollIntoView({
    behavior: "smooth"
  });
})
body{
    margin: 0;
    box-sizing: border-box;

}


    nav.sticky{
        background-color: blue;
        border-bottom: 10px solid black;
    }
    
    nav img{
      width: 10vh;
    }
    
    nav.title-bar{
        background-color: red;
        display: block;
        position: sticky;
        top: 0;
        width: 100%;
        transition: 0.5s;
        height: 50vh;
        z-index: 10000;
        color: white;


    nav.title-bar > *{
            padding: 20vh;
    }

    }
    
    #first{
       background-color: yellow;
    }
    
    #second{
      background-color: green;
    }
    
    #third{
    background-color: blue;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
     <nav class="title-bar">
            <div class="logo">
                <img src="https://picsum.photos/200" alt="logo" id="logo">
                <h1 id="title"><a href=".">My Website</a></h1>
            </div>

                <div class="links">
                    <a href="#first" class="selected">First</a>
                    <a href="#second">Second</a></label>
                    <a href="#third">Third</a></label>
                </div>
        </nav>
    <section id="first">
        <div class="div-1">
            <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Vel mollitia tempora labore, ad laboriosam modi recusandae ipsam tempore quasi tenetur, veritatis, alias pariatur qui doloremque accusamus temporibus doloribus porro aperiam?</p>
            <img src="https://picsum.photos/200/300">
            <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. At maiores sunt voluptatum quas laboriosam, ducimus nesciunt ipsa quis, ullam rerum ipsam consectetur aperiam, mollitia totam aliquid sit exercitationem eius facilis?</p>
            <img src="https://picsum.photos/200/301">
        </div>

    </section>

    <section id="second">
        <div class="div-2">
            <img src="https://picsum.photos/200/302">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum quod, mollitia cumque quisquam itaque earum vel voluptatibus nesciunt quas provident inventore doloribus amet est possimus, consectetur maxime consequatur. Delectus, corporis?</p>
        </div>

        <div class="div-3">
            <img src="https://picsum.photos/200/303">
            <ul>
                <li>aaaa</li>
                <li>bbbb</li>
                <li>cccc</li>
                <li>dddd</li>
            </ul>
        </div>
    </section>>
    
    
        <section id="third">
        <div class="div-2">
            <img src="https://picsum.photos/200/302">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum quod, mollitia cumque quisquam itaque earum vel voluptatibus nesciunt quas provident inventore doloribus amet est possimus, consectetur maxime consequatur. Delectus, corporis?</p>
        </div>

        <div class="div-3">
            <img src="https://picsum.photos/200/303">
            <ul>
                <li>aaaa</li>
                <li>bbbb</li>
                <li>cccc</li>
                <li>dddd</li>
            </ul>
        </div>
    </section>
</body>
</html>

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

Element in Vue not displaying when modal is hidden

Having trouble displaying a Vue component on a modal controlled by semantic ui. The Vue element is not loading or mounting properly. My setup involves Laravel and jQuery with some Vue elements intertwined. I have a hunch that the issue stems from the moda ...

Effortless content extraction between HTML tags using BeautifulSoup in Python

My Weather Data Extraction Project: I'm currently developing a webpage scraper to collect weather information. This is the progress I have made so far: import urllib.request from bs4 import BeautifulSoup # opening the webpage and storing the conten ...

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

Function in jQuery to reference two different divs

I'm currently facing an issue with a code snippet that I have. The requirement is for the user to be able to hover over "Div 1" and/or "Div2" and trigger a red border around both elements simultaneously. Due to the complexity of my WordPress theme, th ...

Unable to handle prepended <img> using Pixastic

I'm encountering a puzzling issue with my website's image display. Currently, I have implemented a jQuery script that successfully scans a folder to gather image sources and displays them as background images on the site. Everything works smooth ...

Navigating through the year selection with your keyboard

By default, a dropdown menu containing years allows for keyboard navigation. For example, if you type in 1992 while the dropdown is selected, it will automatically move to that specific year option. I am curious to know if there is a way to activate a two ...

Exploring the Power of React's Ref API

Currently, I am following tutorials on Udemy by Max where he discusses how to work with Ref Api's in React 16.3. In one of the lectures, he demonstrated creating a ref inside a container class, not App.js, using this.lastref = React.createRef();. He ...

Having trouble with submitting a form using @submit in Vue 3

I am facing an issue with the vuejs @submit.prevent feature in my login form. When I click the login button on my website, it does not work as expected. Even after adding a catch error in the function, the console still shows nothing. Can someone please as ...

Extract information from a URL using Regular Expressions

On my page, I have a list of blog post links: <ul class="postlist"> <li><a href="http://someblog.it/blogpost/7/-----.aspx">Post One</a></li> <li><a href="http://someblog.it/blogpost/32/----------.aspx">Post Two< ...

Click on the child element while it is already being clicked by manually implementing the 'declick' function in Javascript

Hey there, I'm looking for suggestions on a better title for this issue. I couldn't come up with the right wording myself. Problem I currently have a Google Maps element with pointer events set to none, preventing it from being scrolled when ho ...

Troubleshooting issues with mail subscriptions using Ajax and PHP

My Idea for Implementation I successfully set up a subscription form using PHP initially. However, I wanted to enhance the user experience by implementing an Ajax feature that would display a nice image and a "thank you" message without reloading the pag ...

Creating a connection to an external website through a JavaScript function within an Angular application

I am currently working on an Angular application. Within the index.html file, there is a header that contains links to external websites. <a href="#" onclick="getExternalUrl('about.html');">Click here </a> <scr ...

Attempting to retrieve exclusively the checked records in Vue.js

Currently, I am referring to this library for checkboxes. As I delve into the code, I notice how it is declared and utilized. Initially within the el-table, we have @selection-change="handleSelectionChange". They have initialized an empty array ...

Leveraging font awesome ttf in conjunction with scss

I am currently attempting to incorporate Font Awesome with SCSS. @font-face { font-family: 'awesome'; src: url('../../fonts/font-awesome/fa-light-300.ttf') format('ttf'); } Although the path appears to be correct, I am ...

Assistance with the Chakra UI Range Slider in React

I could use some help figuring out where exactly to implement my OnChange and Map functions for mapping JSON data into a Range Slider. Everything seems to be rendering correctly, but I keep encountering an error when I try to move the slider: Unhandled Ru ...

Use PHP to create a new JSON file on the server by submitting a form, then utilize a second form to update

My current goal is to create a json file using a form and then update that file with another form. Both of these processes are handled in the process.php file. I have managed to successfully update the json file if it is named as data.json initially in pro ...

Displaying incorrect symbols with icon fonts

I have successfully integrated icon fonts into my simple web page. Check it out on jsFiddle here My design is similar to this example, but instead of bars, I see a snake icon displayed. How can I fix this issue with the fonts? Here is the code snippet: ...

What is the best way to fill out a mandatory text field within the text area?

I am currently facing a challenge with making the comment field mandatory in my PHP application. Despite my lack of expertise, I have been unsuccessful in finding a solution so far. Below is an example code snippet where PHP generates the comment field. Du ...

Using HTML5 date input on an android browser

As I develop a web page catering to Android users, I have incorporated a date form control for users to input dates. However, I have noticed that on most devices, the native date selector does not pop up. Interestingly, on certain Samsung devices like the ...

Utilizing the controller specified in the template that has been included

Within this snippet of code, I am attempting to utilize a controller named FooCtrl that is defined in the included template app/foo.html, using the directive common.script. angular.module('common.script', []).directive('script', func ...