What is the best way to create a fixed navigation bar that only stays fixed on particular sections of my website?

In my digital portfolio, I have divided it into "4 sections," each represented by a separate scrollable web page. These sections are also known as parts, starting from #part1 up to 4.

For section 1 (#part1), I prefer not to display the navigation bar. However, for sections 2, 3, and 4 (identified as #part2, #part3, and #part4), I would like the navigation bar to be visible.

I found an interesting example site that showcases the kind of navigation bar I want to implement in my portfolio.

I tried grouping sections 2, 3, and 4 together, but removing 'fixed-top' removed the navbar from section 1 while causing navigation bars in sections 3 and 4 to disappear.

Question:


How can I have the navigation bar appear on sections 2, 3, and 4, but remain hidden on section 1?

View my website's code

<body>
    <!-- Page content -->
    <!-- SECTION1 -->
    <section id="part1">
     .
     . (omitted for brevity)
     .
    </section>
    <div class="wrapsections">
        <nav class="navbar fixed-top navbar-light bg-faded">
         .
         . (omitted for brevity)
         .
        </nav>
        <!-- SECTION2 -->
     .
     . (omitted for brevity)
     .
        </section>
        <!-- SECTION3 -->
     .
     . (omitted for brevity)
     .
        </section>
        <!-- SECTION4 -->
     .
     . (omitted for brevity)
     .
        </section>
    </div>
</body>

Answer №1

For a solution in CSS, you can utilize the position:sticky property

CSS

.fixed-top{
      position:sticky;
    }

Find a demo here

I trust this information will be beneficial to you

Answer №2

$(document).ready(function(){
$('.navbar').hide();
  $(".fa.fa-angle-double-down").on('click', function(event) {
        event.preventDefault();
    if (this.parentElement.hash !== "") {
      event.preventDefault();

      // Storing the hash value
      var storedHash = this.parentElement.hash;
console.log(`Stored hash = ${storedHash}`);
      $('html, body').animate({
        scrollTop: $(storedHash).offset().top
      }, 800, function(){

        window.location.hash = storedHash;
      });
    } // End if
    console.log(`Updated hash value = ${storedHash}`);
  });

  $(window).bind('scroll',function(){   
    if ($(window).scrollTop() > 50) {
            $('.navbar').show();
    } else {
            $('.navbar').hide();
    }
  })
});

Feel free to use the updated code provided above and also check out the changes in the js-fiddle link. Thank you.

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

In the production build of Next.js, accessing dynamic routes may lead to a 404 error

Incorporating Dynamic Routing in my next JS project has been a seamless process so far. During development mode, all features are functioning as expected. However, I noticed that when I access a dynamic page for the first time, it loads without any issue ...

Invoke a function within the <img> tag to specify the source path

I have been attempting to achieve something similar to the following: <img id="icon" class="cercle icon" src="getIcon({{item.status}})" alt=""> This is my function: getIcon(status){ switch (status) { case 'Ongoing': ret ...

How can I prevent event propagation in Vuetify's v-switch component?

Currently, I am working with Vuetify and have incorporated the use of v-data-table. Whenever I click on a row within this data table, a corresponding dialog box represented by v-dialog should open. Additionally, each row contains a v-switch element. Howeve ...

What is the best way to terminate a "for await ...of" loop if it fails to finish within a specified timeframe?

Is it possible to stop an asynchronous loop if it doesn't finish within a set time frame? I'm working with the following code: (async()=>{ for await(let t of asynDataStreamOrGenerator){ //some data processing } //some other code I n ...

The background colors are not extending to the full width of the screen

I am facing an issue in my CSS code while trying to create a footer. The background color is not filling the width of the screen, and I had encountered the same problem earlier. Here is how it looks: (https://i.sstatic.net/5VxYU.png) HTML Code: *{ ma ...

What is the best way to apply a CSS class to a ComponentRef that has been generated in Angular 5

I am attempting to dynamically add a CSS class to a component right after its creation by utilizing ViewContainerRef and ComponentFactoryResolver. My goal is to determine the class based on which other Components have already been added to myViewContainerR ...

Connect the input field to a dictionary

Here is an input field: <input id="DeviceId" class="form-control deviceCatalog" data-bind="value:DeviceTemp, valueUpdate: ['blur']" required /> This input is connected to the following viewModel: var ViewModel = f ...

When executing my code to delete a file and remove it from the database, an error message pops up in the console

I've been working on implementing a delete image feature on my website. Although my code successfully deletes the file from the images folder and removes the corresponding record from the database, I encounter an error in the console that prevents me ...

I am in need of assistance in developing an image slider using react.js. Can you help

let projects = [{id: 1, img: "https://scontent-lax3-2.xx.fbcdn.net/v/t1.0-9/117405206_1535037326696077_4967665142447981078_o.png?_nc_cat=111&ccb=2&_nc_sid=730e14&_nc_ohc=XlNXGJF47E0AX8lB1fk&_nc_ht=scontent-lax3-2.xx&a ...

JQuery fails to keep up with the dynamic updates that angularjs effortlessly handles

Dealing with AngularJS has been a learning curve for me. <span data-end-time="{{ productAuctionEnd | date:'yyyy,MM,dd,HH,mm,ss' }},000" class="detail-rest-time js-time-left"></span> As I try to incorporate jQuery into the mix $(".j ...

Scrolling horizontally in a container using the mouse wheel

Is there a way to enable horizontal scrolling in a div using the mouse wheel or drag functionality with jQuery? I attempted using draggable, but it did not work effectively in my specific code scenario. Currently, I have a horizontal scrollbar. Are there ...

What is the significance of utilizing app.set() and app.get() in applications?

Is there a way to simplify this code: app.set('port', (process.env.PORT || 3000)); const server = app.listen(app.get('port'), () => { console.log('Server|Port: ', app.get('port')); }); Here is an alternative ...

Harness the power of the chessboard.js JavaScript library for enhancing your

I'm not very experienced with JavaScript. I'm trying to implement the chessboard.js library, but the chessboard I'm rendering is not showing the pieces, only the board itself. I followed the instructions provided here: How do I use chessboar ...

When coding in JavaScript, the value of "this" becomes undefined within a class function

I'm facing an issue with my TypeScript class that contains all my Express page functions. When I try to access the class member variable using this, I get an 'undefined' error: class CPages { private Version: string; constructor(ver ...

JavaScript is reliant on the presence of the alert() function to properly function

I have a JavaScript function that performs well, except for when I remove or comment out the alert() line. This function is designed to calculate the sum of values in up to 30 fields if they are present and contain a value. Here is an example of the HTML ...

Invoke JavaScript when the close button 'X' on the JQuery popup is clicked

I am implementing a Jquery pop up in my code: <script type="text/javascript"> function showAccessDialog() { var modal_dialog = $("#modal_dialog"); modal_dialog.dialog ( { title: "Access Lev ...

What are some ways to conditionally implement dynamic imports?

Currently, I am working on a project that involves Reactjs + Nextjs. I am facing a situation where I need to dynamically import a component based on certain conditions. For example: const importMyComponent = isLiveBlog => ({ image: isLiveBlog ? i ...

Open the navigation menu by clicking on either the navigation links or anywhere outside of it

Seeking a solution for my mobile navigation menu that closes when clicking outside the links or on one of them, without using jQuery. How can I achieve this with JavaScript ES6? Current code snippet: const navSlide = () => { const burger = docum ...

How to strategically break Bootstrap 5 button groups for different resolutions?

Is there a way to create a line break in a specific place within a button group on a certain screen size? I have a button group with 4 buttons in a row, and I would like to split it into two lines after the first button if there isn't enough space. ...

Using Observables to assign values received from API calls to each element during loop iterations

As I loop through using a foreach loop, I need to call functions that will make async API calls and return values to be rendered in the HTML. The first function getCurrentValue() will return the currentTemperatureRef which should then be assigned to recei ...