Open the menu directly on the visible screen or current location of the webpage when the sticky button is clicked

I have been working on creating a navbar that will scroll down upon clicking a button. Everything seems to be functioning correctly, except for one issue that I can't seem to figure out. The problem is that when my sticky navbar is clicked while at the bottom or middle of the page, it appears at the top of the webpage instead of staying in its current position.

What I am aiming for is for the navbar to behave like the buttons in each navbar on stackoverflow - no matter where on the page they are clicked, the corresponding menu should be displayed.

Here is a snippet of the CSS code I have been using:

#btndiv
{
    background-color: red;
    height: 56px;
    position: sticky;
    top: 0px;
    z-index: 2;
}

#mobilemenu
{
    display: none;
    background-color: whitesmoke;
    position: absolute; 
    width:100%;
}

#mobilelinks
{
    display: block;
    text-align: center;
}
#mobilelinks a
{
    display: block;
    margin: 8px;
}
.innerdiv
{
    margin: 12px; 
} 
.links
{
    float: left;
}
.links a
{
    padding: 12px;
    margin: 0px 12px;
    text-decoration: none;
    color: black;
    font-size: 1em;
    cursor: pointer;
}
.links a:hover, .links a:focus
{
    text-decoration: underline;
}

You can view the progress I've made so far by following this link: https://jsfiddle.net/mahajaved/cans5qe0/16/

Answer №1

Effective Resolution:

View the solution here

Error Analysis

The element with id #btndiv was sticky, but #mobilemenu was not sticking as intended.

As a result, the mobilemenu appeared on top of other elements.

Action Taken

We resolved the issue by moving #mobilemenu inside of #btndiv.

Now both elements are sticky and functioning correctly. Problem solved!

Answer №2

When considering this issue, it's important to remember that the menu opening is connected to the red menu bar you're using. Therefore, its positioning should be based on the location of your menu bar. The initial step involves moving the #mobilemenu div into the #btndiv.

For the most recent version, check out this updated fiddle: https://example.com/abcdefg/

Answer №3

The issue you are experiencing is due to the fact that your mobilemenu is positioned outside of the containing div btnDiv, which serves as the navbar. To resolve this, simply relocate the mobilemenu inside the btnDiv:

function menuvisible() {
  $('#mobilemenu').slideToggle('slow');
}
#btndiv {
  background-color: red;
  height: 56px;
  position: sticky;
  top: 0px;
  z-index: 2;
}

#mobilemenu {
  display: none;
  background-color: whitesmoke;
  position: absolute;
  width: 100%;
  top: 10;
  left: 0
}

#mobilelinks {
  display: block;
  text-align: center;
}

#mobilelinks a {
  display: block;
  margin: 8px;
}

.innerdiv {
  margin: 12px;
}

.links {
  float: left;
}

.links a {
  padding: 12px;
  margin: 0px 12px;
  text-decoration: none;
  color: black;
  font-size: 1em;
  cursor: pointer;
}

.links a:hover,
.links a:focus {
  text-decoration: underline;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="btndiv">
  <button id="menubtn" onclick="menuvisible()">Menu</button>

  <div id="mobilemenu">
    <div class="innerdiv links" id="mobilelinks">
      <a href="home.php#home">Home</a>
      <a href="">About</a>
      <a href="">Courses</a>
      <a href="">Library</a>
      <a href="">Services</a>
      <a href="">Contact</a>
    </div>
  </div>
</div>

<div>Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum, sequi. Possimus, omnis natus. Quos, nostrum ab iste laudantium quod vitae ... culpa vitae! Cum, repudiandae. Temporibus nam voluptatum esse perferendis quam expedita, dignissimos quod aliquid dolore eum consequatur laboriosam quos eius animi aliquam ipsam deserunt officia reiciendis. Harum assumenda velit molestiae necessitatibus aspernatur sed tempora quod.</div>

This adjustment works because now the mobilemenu is contained within the btnDiv, allowing you to set its positioning using properties like position: absolute along with top, right, bottom, and left. These values will be calculated in relation to the position of the btnDiv.

Previously, the position of the mobilemenu was being calculated relative to its parent element, which was the body, causing it to always appear at the top right corner of the document regardless of scrolling.

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

AngularJS enhanced dropdown navigation bar built using Bootstrap styling

I'm currently learning how to implement Bootstrap, but I've run into an issue. I created a dropdown in the navigation bar, but when I clicked on it, the dropdown didn't collapse as expected. The class="dropdown" didn't change to class= ...

What steps should I take to resolve the CSS layout issue specifically on iPhone Safari browser?

It's functional on Chrome desktop However, it has issues on Safari iOS Here is the CSS code snippet .button { border: 1px outset $color3; background: $color1; color: $color4; font-size: 80%; // Reduced size due to uppercase text ...

What are some methods for toggling text visibility in PHP?

I am facing confusion regarding the functionality of this code. Here is the snippet in question : //start date to end date <?php if($show5 < $show6) { ?> <a>show content</a> <?php }?> If both 'start da ...

Having trouble with Material-UI Textfield losing focus after re-rendering? Need a solution?

I am currently utilizing Material-ui Textfield to display a repeatable array object: const [sections, setSections] = useState([ { Title: "Introduction", Text: "" }, { Title: "Relationship", ...

How to prevent all boxes in jQuery from sliding up at the same time

I am encountering an issue with 36 boxes where, upon hovering over the title, the hidden text below it should slide up. However, all 36 boxes are sliding up simultaneously instead of just the one being hovered over. Below is the script I am currently using ...

Notify when the SVG object is clicked based on its identifier

I'm interested in adding more complexity to this project, but before I can proceed, I need to be able to detect when a specific object element containing an SVG image with an ID is clicked. Each object is nested within a div. <div class="grid 18"&g ...

Hide Bootstrap columns for Printing

I am currently working on a webpage layout that consists of two columns. <div class="container"> <div class="row"> <div class="col-md-8 "></div> <div class="d-print-none col-md-4"></div> </div ...

Will synchronous programming on an Express server prevent other users from accessing the page simultaneously?

Currently working on a simple one-page web app that depends on loading weather data from a file. To avoid multiple HTTP requests for each visitor, I have a separate script refreshing the data periodically. In this particular instance, I am using fs.readFi ...

Did I incorrectly pass headers in SWR?

After taking a break from coding for some time, I'm back to help a friend with a website creation project. However, diving straight into the work, I've encountered an issue with SWR. Challenge The problem I'm facing is related to sending an ...

Solving the Challenge of Refreshing Expired Tokens in Azure AD B2C, ASP.NET MVC and JQuery Ajax

I am facing an issue with my web application which is developed using .NET 7.0 and Mvc/Razor. The application is secured using Microsoft Identity libraries and Azure AD B2C. I have successfully added the [Authorize] attribute to the Mvc controllers, enabli ...

Issues with AJAX rendering partially are causing malfunctions

Using AJAX, I am rendering this partial: <% if current_user.profiles_shown_video.where("video_id = ?", params[:id]).count == 0 %> <p class="none"> None </p> <% else %> <ul class="shown_users_list"> <% current_user. ...

Cannot adjust Span content with JQuery

I am currently utilizing Bootstrap and JQuery for my project. HTML <div> <ul> <li><strong> Status : </strong><span id="monitorStatusSpan">1111</span></li> </ul> </div&g ...

Combining Prisma results into a unified object

I am currently working on a project using nextjs 13 and prisma ORM with MongoDB. My task involves fetching roles along with their permissions to create an admin role matrix. Here is the schema for the Role model. model Role { id String @id @de ...

Help! I'm trying to access a property inside event.body in AWS Lambda, but it keeps returning undefined. What

https://i.sstatic.net/467mq.png I've been attempting to retrieve event.body.data, but it keeps returning undefined. I've tried various methods such as JSON.parse(event), JSON.parse(event.body), JSON.parse(event.body.data), JSON.stringify, and mo ...

CSS: Choose elements that have a single parent that matches the attribute selector

I'm relatively new to coding, so please bear with me if this seems like a silly question. I'm currently working on developing a general-purpose scraper to extract product data using the "schema.org/Product" HTML microdata. Unfortunately, I encou ...

Include a lower border on the webview that's being shown

Currently, the webview I'm working with has horizontal scrolling similar to a book layout for displaying HTML content. To achieve this effect, I am utilizing the scroll function. My inquiry revolves around implementing a bottom border on each page usi ...

jQuery failing to execute

Can someone help me figure out why my alert isn't working when a button is clicked using jQuery? I'm not sure if it's a syntax error or something else. <!DOCTYPE html> <html> <head> <title>BETA BLOCKER NET</title& ...

Three.js is not a representation of an object within the THREE.Object3D framework

Can you assist me with this issue? Below is the pertinent information: c9: or (http://) zixxus-github-io-zixxus.c9.io/ and git: https://github.com/zixxus/zixxus.github.io.git Myconsole: "THREE.WebGLRenderer" "69" three.js:17679 "THREE.WebGLRenderer: ...

Having trouble modifying the Input with split() in angularJS

I am faced with a nested JSON object that contains an array as one of its properties. Each item in the array is separated by a ';'. My goal is to use ';' as a delimiter to split each array item and make necessary changes. However, I am ...

Rails 3.1 experiencing issues with JQuery loading

I'm having trouble including my jQuery and other JavaScript files in my views. My Gemfile includes: gem 'jquery-rails', '>= 1.0.12' I am using Rails version 3.1.0 In the header section, I have: <head> <%= stylesh ...