How can you create a sticky navigation bar specifically designed for horizontal scrolling on a website?

I am facing a challenge with a large table that extends beyond the screen, requiring both horizontal and vertical scrolling. My goal is to create a sticky navbar that remains at the top when I scroll horizontally, but hides when I scroll vertically, only to reappear when I scroll back up to the top of the page.

Although I attempted a solution using CSS and JavaScript, the navbar also disappears when I scroll horizontally. It should only be hidden during vertical scrolling.


    <style>
        #sticky {
            position: fixed;
            top: 0;
            width: 100%;
        }
    </style>

    <script>
        var prevScrollpos = window.pageYOffset;
        window.onscroll = function() {
            var currentScrollPos = window.pageYOffset;
            if (prevScrollpos > currentScrollPos) {
                document.getElementById("sticky").style.top = "0";
            } else {
                document.getElementById("sticky").style.top = "-70px";
            }
            prevScrollpos = currentScrollPos;
        }
    </script>

Answer №1

If you want to enable a horizontal scroll bar, you can utilize the CSS property overflow-x: scroll:

#sticky {
      height: 60px;
      display: table-row;
      background: #333;
      position: fixed;
      right: 0;
      left: 0;
      overflow-x: scroll;
}

UPDATE:

Yes, it is possible to apply styles using JavaScript as well:

document.getElementById('sticky').style.overflowX = 'scroll';

Answer №2

To achieve the desired effect, you can utilize position sticky, which functions as a toggle between fixed and relative based on your scroll position.

body {
  margin: 0;
  font-size: 28px;
  font-family: Arial, Helvetica, sans-serif;
  width:200vw;
  height:300vh;
}

.header {
  background-color: #f1f1f1;
  padding: 30px;
  text-align: center;
}

#navbar {
  overflow: hidden;
  background-color: #333;
  width: 100vw;
  left: 0;
  position: sticky;
}

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: #ddd;
  color: black;
}

#navbar a.active {
  background-color: #4CAF50;
  color: white;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div class="header">
  <h2>Scroll Down</h2>
  <p>Scroll down to see the sticky effect.</p>
</div>

<div id="navbar">
  <a class="active" href="javascript:void(0)">Home</a>
  <a href="javascript:void(0)">News</a>
  <a href="javascript:void(0)">Contact</a>
</div>

</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

Customize the border style for the span element

I attempted to use the code below in JavaScript/jQuery to adjust the border thickness. Unfortunately, it seems to be ineffective. Can someone please assist me? //$("span").css({"border":"4px solid green"}); document.getElementById("192.168.42.151:8984_ ...

The color of the text on the Homepage appears differently on iOS Safari

At the top of my homepage, I have displayed the company phone number with white text color. It appears correctly as white on my desktop browsers (Firefox and Chrome), also on my Droid phone, but shows up as dark gray on my iOS phone using Safari. Why is th ...

Utilizing the Onchange Event with Multiple Input Fields in Vanilla JavaScript

I'm working on a website where multiple inputs need to be created dynamically using createElement. Each input can have its own class, id, and other attributes. The main objective is to automatically calculate the overall price whenever a user adds a ...

Is it possible to utilize jQuery's .wrap or .wrapInner to encase a variety of elements within them?

I am working with a HTML structure that looks like this: <section> <item> <ele class="blue" /> <ele class="green" /> <ele class="red" /> </item> <item> <ele class="blue" /> <ele ...

Embed the parent component within the child component

I have two files called Recursive.vue and Value.vue. Initially, when Recursive is the parent component, mounting Recursive within itself works perfectly. Similarly, mounting Value within Recursive and then Value within itself also works fine. However, an ...

What is the reason for the failure of the jQuery code to disable the submit button in the following snippet?

I am working on a feature to disable the submit button in a form when the username, email, password fields are empty. When all of them are filled, I want to enable the submit button. However, the current code is not disabling the submit button as expected. ...

Using HTML and CSS to create interactive icons that change color when clicked, similar to how a link behaves

Have you ever wondered if there's a way to make an icon act like a link when clicked, just like regular text links turning purple? And not just the last one clicked, but every single icon that gets clicked. Trying to use the :visited pseudo was unsucc ...

Element remains stationary and covers full viewport on mobile devices when the page overflows

I am looking to create a fixed element that covers the entire viewport on mobile devices (specifically Chrome and WebView). The CSS code I have is very straightforward: .full { position: fixed; left: 0; top: 0; width: 100vw; height: 10 ...

How to use Selenium-Webdriver (Java Script) to wait for an element to vanish

driver.wait(until.elementIsNotVisible(By.css(".popup-backdrop fade")), 15000); Is there a way to wait for the ".popup-backdrop fade" overlay to disappear before proceeding with element click? I am working with Selenium-webdriver using JavaScript, not Jav ...

Issue: Unable to access 'filter' property of null object

I've been working on a small react dropdown task and it's running smoothly in Google Chrome. However, I encountered an error when testing it on MS Explorer. Even after deploying it on a live server, the issue persisted. The specific error message ...

An unconventional web address was created when utilizing window.location.hostname

I've encountered an issue while trying to concatenate a URL, resulting in unexpected output. Below you'll find the code I tested along with its results. As I am currently testing on a local server, the desired request URL is http://127.0.0.1:800 ...

Failure to send Websocket connection

Currently working on PHP, here's a snippet: $room_array = array(); $room_array[0] = 'room-list'; $room_array['info'] = array('room_name' => $room['room_name'], 'owner' => $username['usernam ...

Utilizing JSON data from Google Maps Matrix with JavaScript

I am trying to fetch the real-time duration of a particular route on Google Maps through my JavaScript code. However, I seem to be stuck. Here's what I have written so far: $(document).ready(function Duration() { var d = new Date(); $.ajax({ ...

I am attempting to display the number of guilds that my bot is currently in through a status update feature, however, the information does not seem to be updating

I need help creating a dynamic status for my Discord bot that updates to show the number of servers the bot is in whenever it joins a new server. This is the current code I have: bot.on('ready', () => { console.log(`${bot.user.username} is n ...

Creating a JavaScript array filled with database data using PHP

Below is a snippet of PHP code used to establish a connection to a database: <?php $host = "localhost"; $user = "admin"; $password = ""; $dbname = "test"; $con = new mysqli($host, $user, $password, $dbname) or die ('Could not connect to the d ...

Is there a way to only allow the active video to play while disabling the others in this Vue 3 and Bootstrap 5 carousel?

I'm currently developing a Single Page Application (SPA) using Vue 3, TypeScript, and The Movie Database (TMDB). Additionally, I'm incorporating Bootstrap 5 for the UI. To showcase movie trailers on the movie details page, I've created the ...

Error: The property "indexOf" cannot be accessed because n is not defined

After rendering a page and retrieving data from Firebase upon clicking a button, I encounter an error upon refreshing the page: Unhandled Runtime Error TypeError: can't access property "indexOf", n is undefined Source pages\[id].js (1 ...

Is there a way to update the background dynamically?

I'm currently developing a weather application and I want the background to change dynamically based on the data retrieved from an API. Initially, I set up a variable and utilized an if statement for this purpose. However, I encountered difficulty in ...

What is the best way to retrieve the column that comes after a specific column?

I have a specific column and I want to extract the subsequent column in the dataset. nhood,column,variablecolumn Treasure Island,3,5 McLaren Park,1,2 Tenderloin,28,112 Lakeshore,14,8 Chinatown,15,103 Although I know the name of the second column, the na ...

Retrieve the chosen item from the autocomplete feature

Unfortunately, I have encountered an issue with this solution as I was unable to get it to work correctly in my code. The objective is to retrieve the selected item and then call another function to utilize it. The script is as follows: <script type=" ...