Menu secured in place within the wrapper

My website is contained in a wrapper with a max width, and I have a fixed side menu that can be toggled with a button.

The problem I am facing is keeping the fixed side menu within the page wrapper. Fixed elements are typically positioned relative to the window rather than the parent element.

Here is an example using position: fixed: https://jsfiddle.net/okavp4p1/

As shown in the link above, the menu extends beyond the viewport instead of staying within the wrapper (grey area).

https://i.sstatic.net/mioNI.gif

To work around this issue, I utilized position: absolute: https://jsfiddle.net/5q3hn1fq/

In this updated version, the menu remains inside the wrapper as intended.

https://i.sstatic.net/SYFFl.gif

However, I had to add extra jQuery code to mimic fixed positioning during scrolling.

// Fix menu
$(window).on('load scroll resize', function() {
    navigation.find('ul').css('top', $(window).scrollTop());
});

Unfortunately, this method causes glitches and lag on most browsers. While the scrolling animation in the example may not show much issues, it becomes very apparent when implemented on a site with more elements.

Check out how it looks like when scrolling down the page:

https://i.sstatic.net/jOaC4.gif

I considered disabling scrolling when the menu is open but I am seeking advice or suggestions from others. Can anyone offer assistance?

Answer №1

If you're looking for a workaround, here's one that might help. You could create an invisible fixed bar at the top using position:fixed with a height of 1px and no background-color.

Inside this bar, you can place your navigation and set it to float:right. By giving the navigation a width of 0 and then transitioning its width on button click to something like 100px, you can achieve the desired effect.

Using jQuery, you can dynamically adjust the height of the navigation to match the window height when resizing the window or showing it.

Check out this JSFiddle for a live example: https://jsfiddle.net/ahmadabdul3/pptggn6v/1/

To avoid any jumping around, keep in mind not to add padding directly to the navigation. Instead, consider wrapping the navigation in a container and setting the nav width to something like 90% to simulate padding.

For a demonstration of how the padding should be handled, refer to this updated fiddle: https://jsfiddle.net/ahmadabdul3/pptggn6v/2/

Answer №2

If you are experiencing issues with performance across various browsers, consider rewriting your function in plain JavaScript instead of using jQuery.

Although I did not observe any jittery movement in Chrome, using the code below can potentially lessen the strain on the browser.

$(window).on('load scroll resize', function() {
    document.getElementById('nav-list').style.top = window.scrollY + 'px';
});

https://jsfiddle.net/hb4zsL6g/

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

Ways to align div elements

I am currently in the process of developing my own custom animation player. Utilizing Three.js for object rendering has been successful so far. However, the challenge lies in incorporating control options at the bottom of the player interface (such as play ...

`Developing data-driven applications with MVC3 using object binding`

Currently, I am facing a challenge with my project that involves using Entity Framework. To provide context on the database model: public class AssetType{ public ICollection<Field> Fields { get; set; } } public class Field{ public int Id {g ...

Some images fail to load on Ember in the production environment

I am facing an issue with my Ember-cli 1.13 application where all images are loading correctly except those in a specific component. The component is named "list-item" and is defined as follows: {{list-item url="list-url" name="List Name" price="240"}} I ...

The AJAX load event listener triggers prior to receiving a response from the server

When working on a script to upload images via AJAX, the process is as follows: a user selects an image using a form file input field. The form contains an onsubmit function that prevents the page from reloading after submission. Within this function, data ...

What is the process for eliminating the hover effect on a Bootstrap button?

I have customized a Bootstrap button in my stylesheet to make it dark, but it still has a hover effect from Bootstrap that I want to remove. How can I get rid of this hover effect? Take a look at the code snippet below for reference: .btn-dark { min-w ...

The alert feature is triggered when any button is pressed

I am dynamically adding buttons and assigning an event to them: $(document).on("click", ".del-but", remove); Within the remove function, I have a confirm dialog that triggers for each button added (3 buttons => 3 times) function remove() { ...

What is the best way to include a specific stylesheet for Blackberry Curve devices based on certain conditions

Is there a method to include a custom style-sheet specifically for the 'Blackberry curve 2007'? Or perhaps implement a redirect that can identify this device and direct them to a different .html page? I'm looking to create a simplified versi ...

Angular-nvd3: maintaining consistent spacing between data points along the x-axis

By default, the scale of the x-axis is calculated from values, resulting in uneven distances between two adjacent points. For example, with an array of values like [1,2,5], there will be different distances on the x-axis for each point, and the x-axis labe ...

Is there a way to dynamically refresh the options in a select dropdown using jQuery?

I'm facing an issue with updating the options in a select element. Here is how my current select element looks: <select id="productId"> </select> Below is the jQuery code I am using: ... if (data.success) { var items = []; $.ea ...

What does it mean in Javascript when b1 is undefined while o1 has a value and is equal to b1?

Having some issues getting variables to work with drop down options on a page. At first, I couldn't even extract a value from the function but managed to do so by removing "var" from o1. Strange thing is, when I type o1 into the js console on chrome i ...

Is there a way to import a module generated by typescript using its name directly in JavaScript?

I am trying to bring a function from a typescript-generated module into the global namespace of JavaScript. The typescript module I have is called foo.ts: export const fooFn = (): string => { return "hello"; }; Below is the structure of my HTML file ...

A guide on determining the return type of an overloaded function in TypeScript

Scenario Here is a ts file where I am attempting to include the type annotation GetTokenResponse to the function getToken. import { ConfigService } from '@nestjs/config'; import { google, GoogleApis } from 'googleapis'; import { AppCon ...

Is there an alternative to the jQuery :contains selector?

How can I choose an option from a drop-down menu based on its text value? When I execute the following code: var desiredText = "Large"; $("#size option:contains(" + desiredText + ")").attr('selected', 'selected'); it ends up selecting ...

Building multiple files in React allows developers to divide their code

Can a React/Redux application be split into modules during webpack build? For example, having a set of components for users and another set for invoices. I want webpack to generate users.js and invoices.js that can be imported into index.html. If I make ch ...

The JQuery JavaScript function fails to complete its execution

Question: How can I resolve the issue where my PHP file returns a large JSON string with approximately 2000 elements, each having 14 child elements? When using jQuery AJAX to fetch the JSON and populate an ID-identified table, the filling process stops mid ...

Personalizing the Navigation Bar

I am in the process of designing the navigation bar for my website that will work seamlessly on both desktop and mobile devices. To view my progress so far, check out this JS Fiddle link Here is the HTML code I have created: <div class="container-flu ...

Efficient Ways to pass information to an Object within a nested function

const http = require('https'); exports.ip = async (req, res) => { const ip = req.body.ip; const ip_list = ip.trim().split(' '); const count = ip_list.length; var execution_count = 0; var success = {}; // **Creati ...

Is there a way to sustain audio playback even after the current track has finished?

I am facing an issue with my code where I am trying to play the next song in a playlist or album after the current one finishes playing. Although I was able to get a song to play, it does not progress to the next one automatically. Below is the snippet of ...

iframe-based cross-site file upload

I created an image uploading API and implemented a jQuery plugin that utilizes an iframe for the upload process. However, due to the API's domain being different, I am unable to retrieve the return data from the iframe. Is there a solution to accessin ...

Transform in-line elements using specific HTML attributes using CSS styling

Can you achieve this with links (a[href="/"]{_/*CSS declarations.*/_})? For instance: #example > .meow span[style="color:red;"] { text-transform: lowercase; } #example > .woof span[title="I'm a dog."] { color: blue; text-decorat ...