How to create a scrolling fixed div that moves horizontally and repositions to the center when the page is maximized

I've been searching for a solution to my problem and have managed to figure out the first part, but there's still one issue that I could use some help with. While I have some knowledge of html, css, and basic php, I'm completely new to javascript / jquery and consider myself an amateur in web design. So, please explain things in simple terms!

My goal is to create a website with a fixed width of 960px that is centered in wider browser windows. To achieve this, I'm using the following CSS:

#container {
 width:960px;
 margin:auto;
}

This CSS code is working fine.

At the top of this div, I want to have a horizontal menu that stays fixed in place and floats above the rest of the content on the page. The menu should be 960px wide and remain at the top of the viewport even when the user scrolls down vertically.

When the window is wider than 960px, the following CSS works well:

#top {
 width:960px;
 position:fixed;
 top:0;
}

The problem arises when the window is resized to less than 960px wide. In such cases, the fixed menu remains stuck to the left side of the screen while the main content area scrolls to the right, making some parts of the menu inaccessible.

After looking for a solution, I came across this thread, which suggested using the following jquery code:

$(window).scroll(function () {
 $('#top').css('left', -($(window).scrollLeft()));
});

This jquery code adjusts the left positioning of the #top div as the user scrolls horizontally. It seemed like a perfect solution for my needs. After some trial and error, I added the script inside my body tags:

<script src="jquery.js"></script>
<script type="text/javascript"> $(window).scroll(function () {
   $('#top').css('left', -($(window).scrollLeft()));
});
</script> 

Everything worked well until I encountered another issue. When the window is resized back to being wider than 960px, the floating menu remains stuck to the left side rather than moving back to the center along with the main content. This disrupts the layout and misaligns the menu with the rest of the content.

I need a way to remove or reset this CSS adjustment as soon as the browser window exceeds 960px in width and the horizontal scrollbar disappears.

Is there a javascript / jquery solution for this problem? As a beginner in this field, I haven't had much luck finding a solution on my own...

Any suggestions or assistance would be greatly appreciated!

Answer №1

Have you considered enhancing your jQuery code with this addition?

$(window).resize(function(){
    if ($(window).width() > 960) {
        $('#top').css('left', 'auto');
    } else {
        $('#top').css('left', -($(window).scrollLeft()));
    }
});

Would you like to test it out and see if it resolves your issue?

If left scrolling detection is what you need, here's a snippet for that as well:

var lastScrollLeft = 0;
$(window).scroll(function() {
var documentScrollLeft = $(document).scrollLeft();
if (lastScrollLeft != documentScrollLeft) {
    //your code here
    $('#top').css('left', -($(window).scrollLeft()));

    lastScrollLeft = documentScrollLeft;
}
});​

Answer №2

Hooray! Success at last! It just goes to show the power of a fresh mind in the morning. All it took was a simple "if" statement added to the code to make the menu scroll to the left.

A huge shoutout to tsdexter for the help!

$(window).scroll(function () {
 if (($(window).scrollLeft())>0) {
  $('#top').css('left', -($(window).scrollLeft()));
 }
});

$(window).resize(function(){
 if ($(window).width() > 960) {
  $('#top').css('left', 'auto');
 }
});

Now everything seems to be running smoothly on Firefox - fingers crossed for the other browsers too!

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

When the mouse hovers over, include a fade-in effect for the image

I am working with two overlapping images and have successfully implemented a function to display the second image on mouse hover. However, I am struggling to incorporate a CSS transition property for a smoother image transition effect. Currently, when the ...

I have observed that the form on an ASP.NET MVC Partial View can only be submitted after pressing the Enter key twice on the

**** Update - This issue seems to be specific to MS Edge. It functions properly with just one Enter key press on Chrome and Firefox.** I encountered a strange problem where a form only gets submitted after pressing Enter key twice in a text box. The form ...

The styles are not being rendered on the Angular application

I have successfully implemented a Modal service with working HTML/CSS (Check it out on StackBlitz) div.cover { align-items: center; background-color: rgba(0, 0, 0, 0.4); bottom: 0; display: flex; justify-content: center; left: 0; ...

What is the best way to structure JSON data in JavaScript in order to effectively utilize a service?

I am attempting to connect to a service and have confirmed the correct connection, but I am encountering an error. I suspect that the JSON format may be incorrect. ERROR: net::ERR_ABORTED 500 (Internal Server Error). The technology being used is Jquery A ...

Attempting to adjust the background colors of divs in a specific order

I am currently experimenting with the JQuery jquery.animate-colors-min.js plugin to create a sequential change in background color for multiple div boxes. $('#firstbox').animate({ backgroundColor: "#f6f6f6" }, 'slow') Animating the fi ...

Having trouble with the auto width CSS for the center section of my webpage

I am facing an issue with assigning widths to my divisions using the CSS calc property. Despite setting the width for the first and last divisions, I am unable to allocate any width to the middle division. HTML: <div style="width:400px;"> <div ...

Is there a way to ajax multiple forms simultaneously?

I'm facing an issue with my PHP code that generates multiple forms: <?php while($result = $mods->fetch()) { echo "<form><input type='text' name="variable-name" /><input type='submit' name='submit&apos ...

The integration of HTML and CSS using ng-bind-html appears to be malfunctioning

<ion-item ng-bind-html="renderHtml(word[key])"> </ion-item> When referring to word[key], it represents: <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> This is the CSS being u ...

What steps should I take to resolve the problem while in Quirks mode?

My current design includes an element with a width of 200px, along with left and right padding of 100px each. However, I have observed that in IE7, IE8, and Firefox 4, the padding is being added to the total width of the element. On the other hand, in IE ...

Tips for retrieving an element that has been dynamically added to the page in jQuery after it has loaded

Here is the code I used to dynamically add list items to an unordered list after the page has fully loaded: <ul id='hints'></ul> This jQuery script is responsible for adding a new list item to the ul element once the page has finis ...

CSS text width going from left to right

I am attempting to create a text fade effect from left to right, inspired by the technique discussed in this answer. However, I would like the text to be concealed behind a transparent background div instead of the white background used in the example. I ...

Webix UI - Struggling to create dynamically responsive components during screen resizing

Can anyone guide me on how to make my Webix UI control responsive in the free version available at ? It seems to be acting unpredictably due to the AngularJS integration code I'm using. I have attempted various solutions like media queries, redraw, a ...

Challenges with Scaling HTML5 Video onto Canvas

Attempting to extract a frame from an html5 video to generate a thumbnail, but encountering peculiar outcomes when the image is rendered onto canvas. The issue lies in the fact that the canvas displays only a greatly magnified portion of the video! Refer ...

Is it possible to adjust the size of a p5.js canvas within a bootstrap Div container?

I am attempting to incorporate a p5js canvas into a bootstrap grid structure. My goal is to have each div within the grid contain its own unique p5js canvas, which should adjust in size when the browser is resized. Below is my bootstrap grid setup, showca ...

Slide up using jQuery to the left direction

I am looking to design a weekly calendar that slides the old week left or right when switching to a new week. Does anyone have any suggestions on how I can implement this feature? I'm currently struggling to come up with a good solution. Any help is ...

The functionality of the jQuery plugin for displaying a div element is ineffective unless an alert is placed in

I'm puzzled by this situation. I've been working on a jQuery plugin to retrieve data from my MongoDB database and display it back. Here's a snippet of the code... (function() { var result1; var image1; $.fn.showRecs = function() { var ...

Rows within distance

There seems to be too much space between the grid rows. I tried adding more photos or adjusting the height of the .image class to 100%, but then the image gets stretched out. The gap between items with classes .description and #gallery is too wide. When ...

Transfer the information of a selected element to a different element

Hello, I am trying to transfer content from a child element to another element. In my HTML setup, there is a hidden div named "DetailsExpanded" and multiple items called "IconWrapper". When an "IconWrapper" is clicked, I want to copy the content of its "I ...

Switch up the Yii ListBox default onChange event to utilize AJAX with onClick instead

Below is the code I have for a <select> element: $htmlOptions = array( 'size' => '20', 'ajax' => array( 'type' => 'POST', 'url' => Y ...

What causes the button to move down when adjusting the font in a textarea?

I'm intrigued by the reasons behind this css snippet: select, input, textarea, button { font:99% sans-serif; } that causes the 'submit' button to be pushed below the textarea and positioned at the bottom left corner on this particular ...