The fixed position feature seems to be malfunctioning

I'm attempting to incorporate the persistent header feature demonstrated in this tutorial: http://css-tricks.com/persistent-headers/

Here's My Code:

    <div class="col-md-4 col-sm-4 col-xs-12 postRight persist-area">
       <h2 class="persist-header">rgergergerg</h2>  
       <div class="nom-img">
         <a href="ergeg.html"><img src="img/ergerg.jpg"></a>
       </div>
       <div class="tag-nom postCenter"> <a href="#"><img src="img/erg.png"></a>
         <h4><a href="#">serger</a></h4>
       </div>
    </div>

<div class="col-md-4 col-sm-4 col-xs-12 postRight persist-area">
       <h2 class="persist-header">rgergergerg</h2>  
       <div class="nom-img">
         <a href="ergeg.html"><img src="img/ergerg.jpg"></a>
       </div>
       <div class="tag-nom postCenter"> <a href="#"><img src="img/erg.png"></a>
         <h4><a href="#">serger</a></h4>
       </div>
    </div>

Using jQuery

var clonedHeaderRow;

       $(".persist-area").each(function() {
           clonedHeaderRow = $(".persist-header", this);
           clonedHeaderRow
             .before(clonedHeaderRow.clone())
             .css("width", clonedHeaderRow.width())
             .addClass("floatingHeader");

       });

       $(window)
        .scroll(UpdateTableHeaders)
        .trigger("scroll");




    function UpdateTableHeaders() {
       $(".persist-area").each(function() {

           var el             = $(this),
               offset         = el.offset(),
               scrollTop      = $(window).scrollTop(),
               floatingHeader = $(".floatingHeader", this)

           if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
               floatingHeader.css({
                "visibility": "visible"
               });
           } else {
               floatingHeader.css({
                "visibility": "hidden"
               });      
           };
       });
    }

CSS Styling

.floatingHeader {
  position: fixed;
  top: 0;
  visibility: hidden;
}

The issue I'm encountering is that the fixed positioning is not functioning as expected. The header moves up instead of staying fixed. What could be causing this problem?

Answer №1

There is a much simpler way to handle this rather than the complicated method shown above.

All you really need is to add one extra div to save header size and prevent page stuttering.

<div class="persistent">
   <nav>
      <ul>
         <li><a href="#alfa" class="button"><span>ALFA</span></a></li>
      </ul>
   </nav>
</div>

<div class="persistent">
   <nav>
      <ul>
         <li><a href="#beta" class="button"><span>ALFA</span></a></li>
      </ul>
   </nav>
</div>

After that, you just need a simple piece of jQuery to make it work.

function fixMenu()
{
  $('.persistent').each(function(){

    var menu_place = $(this).offset().top;
    var menu = $(this).find('nav'); 

    $(window).scroll(function(){

        var scroll_top = $(window).scrollTop(); 

        if ( scroll_top > menu_place )
            {
                menu.css({ 'position': 'fixed', 'top':0 });
            }
        else
            {
                menu.css({ 'position': 'relative' }); 
            }
    });
}

Simply call the function fixMenu() from the Document ready section.

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

Can the content inside HTML tags be susceptible to XSS attacks?

While working with Codeigniter, I have noticed that the xss_clean() function is replacing tab characters with a single space character. This behavior ends up causing issues when the content is later displayed within <pre><code></code>< ...

Change the image size as you scroll through the window

While my opacity style is triggered when the page is scrolled down, I am facing an issue with my transform scale not working as expected. Any suggestions on how to troubleshoot this or any missing pieces in my code? Codepen: https://codepen.io/anon/pen/wy ...

What is the best way to transfer a PHP string to JavaScript/JQuery for use in a function?

Within my PHP code, I have the following: $welcome = "Welcome!"; echo '<script type="text/javascript">addName();</script>'; Additionally, in my HTML/script portion: <a id="franBTN"></a> <script type="text/javascript ...

Error: The object #<HTMLCollection> does not support the 'tags' method

While trying to troubleshoot this issue, it seems like I haven't been able to pinpoint the simple solution. This particular javascript menu works perfectly in IE, however in Chrome, there is an error when trying to open the menu with a first-level cli ...

Show the total of a JavaScript calculation in a designated input box

Is there a way to show the total sum of this calculation in an input field? function calculateSum1() { var sum = 0; //loop through each textbox and add their values $("input.miles").each(function() { //only add if the value is a number ...

What is the process for generating a variable script within an HTML tag using document.write?

Here is the code snippet: <script>var posterimage=/images/videos/intro/iamge01.png;</script> <script>document.write('<video controls="controls" height="300" id="video-playlist" poster="VARIABLE" preload="none" src="video.mp4" wid ...

Tips for passing the name of a success function as a parameter in an AJAX request

My challenge is to create an AJAX call as a single function, where I pass the success function name as a parameter. Here's the function that I attempted: function MakeApiCall(dataText, apiName, functionName) { $.ajax({ url: apiUrl + apiName, ...

What is the best way to create a toggle effect for a <nav> bar that appears from beneath a div?

I need assistance with a navigation setup where the nav (located inside the header) needs to be connected to the bottom of a div named .menu_bar. The desired behavior is for the nav to slide down from directly underneath the .menu_bar when toggled, but cur ...

The side menu in Bootstrap dropdown experiences a one-time functionality

When navigating through a responsive top menu with Bootstrap, everything works seamlessly - from toggling the menu to dropdown functionality. However, I encountered an issue with the side menu as nav-pills used to select tab-panes. <div class="containe ...

Issues with the display property

After setting the display of a div tag as none in the style property, I am trying to show it based on an on-click function. However, the issue I am facing is that when I click on the function, the div displays for a brief moment then disappears again. Ca ...

Repeating nested items

I'm experiencing difficulty with repeaters. I'm attempting to display a list of appliances under unique categories from my database. The category names repeat correctly, but the appliance names are repeating for all categories (meaning all catego ...

What's the best way to make two buttons appear side by side on a webpage?

I need to have my two buttons, Update and Cancel, displayed next to each other on the same line. Currently, there is a gap between the two buttons as shown in the attached image. Below is the HTML code I am using: <div class="form_block span2"> ...

Filtering multiple custom post types in Wordpress with custom taxonomies using Ajax results in the issue where newly created posts are not displayed in the response

Update: I just figured out the solution to my own problem. If anyone can assist in adding pagination to the response, I'd be happy to treat you to a pint of your choice! :) There's some code that needs tidying up here, but I'll get to it lat ...

Alignment issue with React JSX background position; image not centered on the right in Material UI Grid item

I've recently completed a single-page website portfolio, but I'm encountering an issue with setting the background position of the home screen to center right. You can view my site here: Here is the link to my repository: https://github.com/Bolm ...

Mask the "null" data in JSON

I'm currently working with a JSON file and trying to display it in a bootstrap table. Check out the code snippet I've been using: $(document).ready(function(){ $.getJSON(url, function(data){ content = '<h1><p class="p1 ...

Ways to determine if a class is a part of the bootstrap framework

Is there a way to verify if a class like mt-3 or table-left is part of the bootstrap framework? Are there any online resources, tools, or plugins in VSCode that can assist me in determining if a class is a predefined bootstrap keyword? ...

Retrieve data from XML file using ThickBox

How can I dynamically load content from an XML file into a DIV when a user clicks on specific links? I was successful in loading the correct content by matching arguments passed through a function invoked onClick. Now, I am attempting to display this conte ...

What is the method for calculating values entered into dynamic input fields?

I am facing a slight issue with my HTML form code... Within my code, there are several input fields that are being generated dynamically. Each dynamic input field contains a numerical value which I need to use for mathematical calculations. The calculati ...

Having trouble with either posting a JSON using $.ajax() or reading it using PHP?

I'm struggling to identify the issue at hand. Here's my JavaScript function for sending JSON data: function send(var1, var2) { var result; att = window.location; $.ajax({ 'crossDomain': true, 'type&apos ...

Issue with querying and ordering products in Django using Python when passing values through the GET request

I have been working on a project where I need to filter products and sort them by price in ascending and descending order. Here is the code snippet from my view: def is_valid_queryparam(param): return param != '' and param is not None def f ...