When you start scrolling down, the JavaScript menu will cleverly disappear, only to re

I am facing an issue with my menu, which is a normal block-displayed div. There is another div with annotation above it. I want the menu to stick to the top as fixed when scrolling down, but immediately hide itself. The goal is for the menu to appear when the user stops scrolling, disappear when the user scrolls up, reappear when they stop again, and continue this pattern - always appearing when there is no scrolling activity.

Can anyone provide assistance with this?

Below is the code for my menu:

<div class="menu">
      <div class="menu_tab">
      <div class="wrapper">
            <div class="obsah">
                <div class="kolonky" id="strana">
                     <a href="./"><div class="logo"></div></a>
                </div>
                <div class="kolonky" id="stred">
                    <div class="rozbalit"><a href="obchod.php" id="srdce">Obchod</a>
                        <nav>
                            <a href="priprava_navod.php">Jak připravit matcha čaj</a>
                            <a href="jakaje.php">Jak vychutnat matcha čaj</a>
                            <a href="recepty.php">recepty</a>
                        </nav>
                    </div>
                    <div class="rozbalit"><a href="poznejte.php">poznejte matcha</a>
                        <nav>
                <a href="priprava_navod.php">Jak připravit matcha čaj</a>
                <a href="jakaje.php">Jak vychutnat matcha čaj</a>
                <a href="recepty.php">recepty</a>
              </nav>
                    </div>
                    <div class="rozbalit"><a href="priprava_navod.php">příprava</a>
                        <nav>
                <a href="priprava_navod.php">Jak připravit matcha čaj</a>
                <a href="jakaje.php">Jak vychutnat matcha čaj</a>
                <a href="recepty.php">recepty</a>
              </nav>
                    </div>
                    <a href="clanek.php">blog</a>
                    <a href="pribeh.php">o nás</a>
                </div>
                <div class="kolonky" id="strana">
                    <div id="uzivatel">
                        <a href="ucet.php" id="prihlaseni_otevri">Jaroslava B</a>
                        <nav class="uziv_info">
                            <a href="ucet.php">Moje objednávky</a>
                            <a href="ucet.php">Moje adresy</a>
                            <a href="ucet.php">nákupní košík</a>
                            <a href="#">odhlásit</a>
                            <a href="#">nastavení</a>
                        </nav>
                </div>
                <a href="#"><div class="kosik">
                    <span>15</span>
                </div></a>
                <span id="jazyky">CZ</span>
                </div>
            </div>
      </div>
    </div>
    </div>


.hidden_scr{
    display: none !important;
}

.menu{
    width: 100%;
    background: transparent;
    transition-duration: 0.3s;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

.menu.cloned{
    background: rgba(255,255,255,0.8);
    z-index: 5;
}

.menu_tab{
    width: 60%;
    margin: 0px auto;
    padding: 20px 0px;
    display: table;
    text-align: center;
    vertical-align: middle;
    table-layout: fixed;
    background: transparent;
}

.menu_wr{
    display: inline-block;
    margin-bottom: -5px;
}

.menu_wr.grey{
    background: #edecf0;
}

.menu.grey.cloned{
    background: rgba(255,255,255,0.8);
}

.menu .obsah{
    display: table-row;
}

$('.menu').addClass('original').clone().insertAfter('.menu').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','3').removeClass('original').hide();

scrollIntervalID = setInterval(stickIt, 10);


function stickIt() {

  var orgElementPos = $('.original').offset();
  orgElementTop = orgElementPos.top;               

  if ($(window).scrollTop() >= (orgElementTop)) {    
    orgElement = $('.original');
    coordsOrgElement = orgElement.offset();
    leftOrgElement = coordsOrgElement.left;  
    widthOrgElement = orgElement.css('width');
    $('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement).show();
    $('.original').css('visibility','hidden');
  } else {
    $('.cloned').hide();
    $('.original').css('visibility','visible');
  }
} 


var lastScrollTop = 0;
// element should be replaced with the actual target element on which you have applied scroll, use window in case of no target element.
window.addEventListener("scroll", function(){ // or window.addEventListener("scroll"....
   var st = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
   if (st > lastScrollTop){
       $('.menu.cloned').addClass("hidden_scr");
   } else {
      $('.menu.cloned').removeClass("hidden_scr");   
   }
   lastScrollTop = st;
}, false); 

Answer №1

Task completed :)

let scrollEvent;
let previousScrollPosition = 0;
const scrollThreshold = 5;
const navHeight = $('.menu').outerHeight();
$(window).scroll(function(event){
    scrollEvent = true;
});
setInterval(function() {
    if (scrollEvent) {
        checkScrollState();
        scrollEvent = false;
    }else{
      $('.menu').removeClass('nav-up').addClass('nav-down'); 
    }
}, 250);
function hasScrolled() {
    let currentScrollTop = $(this).scrollTop();
    if(Math.abs(previousScrollPosition - currentScrollTop) <= scrollThreshold)
        return;
    if (currentScrollTop > previousScrollPosition && currentScrollTop > navHeight){
        $('.menu').removeClass('nav-down').addClass('nav-up');
    } else {
        if(currentScrollTop + $(window).height() < $(document).height()) {
           $('.menu').removeClass('nav-down').addClass('nav-up');
        }
    }

    previousScrollPosition = currentScrollTop;

    if(document.body.scrollTop === 0){
      $(".nav-up").css("background", "transparent");
      $(".nav-down").css("background", "transparent");
    }else{
      $(".nav-up").css("background", "rgba(255,255,255,0.9)");
      $(".nav-down").css("background", "rgba(255,255,255,0.9)");
    }
}

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

Get a calendar that displays only the month and year

I am looking to incorporate two unique PrimeFaces calendars on a single page. The first calendar will display the date, while the second one will only show the month and year. To achieve this, I have implemented the following JavaScript and CSS specifica ...

Display a window.confirm alert to prevent any unauthorized changes to the URL

Looking to implement a feature that prevents changing the URL from my component. The goal is to display a message and allow users to choose between canceling (no change to URL) or confirming (change the URL). How can I achieve this in the upcoming 13.4 ver ...

How can a dialog be displayed using a template in Onsen UI in a proper manner?

I am having trouble displaying a dialog in my Angular app with Onsen UI 1.3.6. Whenever I try to show the dialog, I encounter a 404 Not Found error. This is the JavaScript code I am using: ons.createDialog('iconselector.html').then(function(dl ...

PHP processing and converting to a string output

I have a PHP page (content.php) that includes plain HTML and content accessed via PHP variables <html> <head> </head> <body> <h1><?php echo $title; ?></h1> </body> </html> ...

Calling ASPX method remotely and receiving undefined data

I'm still fairly new to ASP.NET and web services. I've encountered an issue where I am calling a web service from a *.aspx page, and the web service is returning the correct output. However, when I call the *.aspx method from an external HTML pag ...

Looping through JSON data in jQuery outputs the value 9 when paired with the text() method

I have retrieved JSON data that is structured as follows: { "solution": { "1": { "cell-1": "1", "cell-2": "2", "cell-3": "3", "cell-4": "4", "cell-5": "5", "cell-6": "6", ...

Avoiding errors caused by higher order array methods

Is there a way to avoid errors when filtering data? The function below may encounter issues at conversationMember.Name.toLowerCase() if conversationMember is not present. This function is part of a computed property in a Vue application. Feel free to ask ...

Arrange the footers in the bootstrap card deck to be perfectly aligned at the top

Using bootstrap 4 to showcase cards has been successful, but there is an issue with footers that have varying content lengths. Instead of the footer adjusting its position based on the content, is there a way to keep the tops aligned while pushing the cont ...

displaying data in a table - adjust cell contents for smaller screens

I am currently designing an admin page using Bootstrap 5. I have implemented a data table with the following contents: On larger screen sizes: https://i.sstatic.net/2a9C1.png For smaller screen sizes (mobile phones), I have collapsed the action button as ...

Issue with SideNav function in MaterializeCss following recent update

After updating the css/js files of the Materializecss design in my project from v0.97.5 to v0.97.8, I noticed that my SideNav isn't functioning correctly anymore. When I try to click on the menu, it slides out but the dark overlay covers the entire sc ...

Unraveling the mystery of decoding a jwt token

Every time I attempt to validate a user token, I keep encountering Error 500. function verifyToken(req, res, next) { if(!req.headers.authorization){ return res.status(401).send('Unauthorized request') } let token = req.headers.authorization. ...

I am struggling to comprehend the code for a PHP form that triggers a JS OnUpdate event, which then uses AJAX to retrieve data from MySQLi

I want to give a special thanks to Alon Alexander for providing the JS and AJAX code, even though I don't fully comprehend it. I am more comfortable using PHP/JS without jQuery, but I am struggling to make it function as intended. My current issue in ...

Storing additional data from extra text boxes into your database can be achieved using AJAX or PHP. Would you

A dynamic text box has been created using Jquery/JavaScript, allowing users to click on an "Add More" button to add additional input boxes for entering data. However, a challenge arises when attempting to store this user-generated data in a database. Assi ...

Regardless of the circumstances, the Node.js PATCH request will always run

Apologies if the title is unclear, I struggled with how to phrase it. I encountered an issue with a PATCH request designed to update a value in my database: although it returns a "working" status (200), the actual update does not occur. I have a .route(&ap ...

Why is it that my for loop produces the accurate result, yet my forEach function fails to do so?

Hey there, I'm new to SO and seeking some guidance. I have a task where I need to create a function with two parameters - an array of strings and a string to potentially match within the array. I've developed two versions of the function: one us ...

What is the correct way to apply a consistent background color to all elements within a container?

Appreciate the prompt responses to my previous inquiry. "I am looking to have a banner on my webpage that contains left-aligned text and right-aligned image, taking up the full width of the page." I neglected to specify that I would like the entire "bann ...

How to enable multiple selections in a Bootstrap 5 form-select, but restrict users to selecting only one

I am looking to create a modal with a list of options where only one option can be selectable. The default form-select is a dropdown menu that requires an unnecessary click, which I want to avoid. I would like all options to be displayed without the need f ...

Modify the background hue of a personalized WordPress HTML block using supplementary CSS styling

My current challenge involves modifying the background color of a specific custom HTML WordPress block. However, when I make changes to one block, it affects the background color of all other custom HTML blocks on different pages. Here is the CSS code I a ...

Having trouble extracting data from a particular cell within an HTML table using jQuery

I am struggling to extract row data from a table for utilization in a modal. Provided below is my code for Views. <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css"> <link href="@Url.Content(" ...

Angular animation will be triggered when the user clicks using ng-click

In my Angular project, I'm looking to implement an animation that will enlarge the size of an image. Below is the code snippet: <div class="card"> <div class="item images-parent"> <img src="img/carryout-icon.jpg" class="left-image" ...