Ensuring that a "position: fixed" div stays horizontally aligned when the window is resized

I am working on a responsive two-column website with a fixed sidebar that changes its position when scrolling. Here is the CSS styling:

#sidebar {
padding: 5px;
width: 200px;
float: left;
background-color: yellow;
}

.fixed {
position: fixed;
padding: 5px;
background-color: yellow;
}

.span8 {
padding: 5px;
width: 400px;
float: left;
background-color: blue;
}

For the JavaScript functionality: var position = $('#sidebar').position(); var offset = $("#sidebar").offset();

    $(window).scroll(function() {          

        if ($(window).scrollTop() > offset.top) {
            $('#sidebar').addClass('fixed');
            $('.fixed').css("top", 0);  
            $('.fixed').css("left", position.left);
         } 

        else {
            $('#sidebar').removeClass('fixed');

        }


    }); 

Below is the HTML structure:

Welcome to My Website

<div class="span8">
  <h4>Main Content Area</h4>
  <p> Your main content goes here... <p>
</div>
<div id="sidebar">
  <h4>Hello!</h4>
  <p>This is a fixed sidebar that becomes fixed on scroll.</p>
</div>

While everything works fine, you can view it in action on jsfiddle here. However, one issue remains - when resizing the window, the sidebar maintains its original horizontal position. I am struggling to make it responsive on resize. Any guidance on this matter would be highly appreciated!

I find it frustrating that jsfiddle displays it perfectly but the actual browser implementation is different. Your assistance would be greatly valued.

Sincerely, Lennart

Answer №1

While I couldn't replicate the issue you're experiencing, it seems to be working fine on my end. However, there are instances where it blinks and disappears sporadically.

Consider these suggestions:

1) Have you thought about using pure CSS? The following code, without any JavaScript, works flawlessly for me:

#sidebar {
padding: 5px;
width: 200px;
background-color: yellow;
position:relative;
left:410px;
top:0;
}


.span8 {
padding: 5px;
width: 400px;
float: left;
background-color: blue;
position:absolute;
}       

2) Regarding this line of code:

$('.fixed').css("left", position.left);

It will only function correctly if position.left is set to 0. To ensure it works under all circumstances, specify it in pixels like so:

$('.fixed').css("left", position.left + "px");

3) Although untested, if your original code is functional for you, consider wrapping your positioning logic into a function and then invoking this function on both window scroll and resize events:

function positionSidebar() {
    var position = $('#sidebar').position();
    var offset = $("#sidebar").offset();    

    if ($(window).scrollTop() > offset.top) {
        $('#sidebar').css('fixed');  
        $('#sidebar').css("left", position.left);
     } 

    else {
        $('#sidebar').removeClass('fixed');
    }       
}

$(window).scroll(function() {         
    positionSidebar();
}); 

$(window).resize(function() {         
    positionSidebar();
});     

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

Creating a series of progress bars in Bootstrap that feature labels positioned to the left and moving towards the right

I am trying to create multiple progress bars using Bootstrap 4 with labels or text on the outer left side. Currently, the bars are appearing like an inverted stair when multiple bars are added. https://i.sstatic.net/zHhfX.png Here is the code I have so f ...

How can I prevent the background image from overlapping the footer?

Click here for image Live version can be found at this link The background image extends beyond the footer. body { background-image: url(../img/planet.jpg); background-repeat: no-repeat; background-size: cover; } Footer: .footer { padd ...

Ensure that the div is set to start on a new line without causing any sudden jumps to the

I have 3 divs that I want to display side by side. If the text inside each div gets too long, I would like it to break to a new line and have the next div stay beside it. <div style="float: left;">This is some text</div> <div style="flo ...

The Jquery Countdown plugin fails to initialize

Currently struggling with getting the jquery Countdown plugin to work for a 12-day countdown. Despite all efforts, the countdown does not seem to start and I am at a loss on how to troubleshoot this issue. After searching online extensively, I have yet to ...

Is it possible to change text dynamically with an input box using JavaScript?

Is there a way to use JavaScript to create two input boxes for text replacement? Instead of constantly editing code to replace different text, I am looking for a simple user interface with Input Box A, Input Box B, and a button. The first input box will ...

I'm attempting to create a text toggle button for displaying more or less content

I am currently working on implementing a show more/show less button feature. However, the current version is not very effective as I only used slicing to hide content when the state is false and display it all when true. Now, my goal is to only show the ...

aligning content that has exceeded the boundaries

I have a list of dynamically created <a> tags without text, to which I apply background images. These icons are displayed within a <div> container using the float: left; style. As the row of icons becomes too long, it overflows and starts a ne ...

Problem with Fancybox in Internet Explorer

For a recent project, I needed to incorporate Fancybox with manual image call using a JSON list. The code snippet below illustrates how this can be done: $("#big_img a").click(function(e) { e.preventDefault(); jsonObj = []; var ac ...

A creative CSS technique to eliminate borders from ul elements without relying on the calc() function

I'm currently using the top bar component from Zurb Foundation and have added a 1px border at the top and a 3px border at the bottom of the nav tag. However, I am facing height issues because the ul menu inside is set to 100% height. What would be th ...

Unveiled Content and Jquery: Triggering with a Double Click

Despite similar questions being asked, I wanted to present my query in a more concise manner. To better illustrate my issue, I have replicated it on jsfiddle (link provided below). The jquery event I am dealing with is: $(document).ready(function () { ...

The Django view function is failing to add new records to the database

Whenever I attempt to create a record in the FinTransDetail table as an admin, I encounter errors. This is preventing me from adding records successfully. Any assistance in resolving these issues would be greatly appreciated. Additionally, since I am unabl ...

How can I alter the background color of the entire header in Ionic?

Having some trouble changing the color of my header. I successfully changed the color of the white header, but not the black header where the time is displayed. I know this is beyond Ionic and part of Android, but I have seen other apps that are able to ch ...

How can I make a single <input> element that can handle both files and urls simultaneously?

Is there a way to enable my users to import both local and remote files using just one input field? A possible solution, inspired by Stackoverflow, is to implement tabs: Another approach could be using radio buttons like this: <style> .display ...

"Enhance user experience with Bootstrap's sleek select feature embedded

I recently purchased the "My City" theme, which is based on Bootstrap. The issue I am facing is with the search box that comes with a dropdown button next to it. I want to change the dropdown button to a select option instead. However, when I try to simply ...

How can I make columns with a max-width expand fluidly?

I am currently using a fluid/responsive column layout that looks like this: .row{ float:left; max-width:960px; width:100%; } .column{ float:left; margin:0 15px; } .column:first-child{ margin-left:0; } .column:last-child{ mar ...

Unlocking the Power of Global Variables in HTML Pages with JTemplate and jQuery

Currently, I am utilizing jtemplate (jquery) and have an htm file structured as follows: <table width="100%" border="0" cellpadding="0" cellspacing="2"> <tr class="dark_color"> <th> Offer </th> & ...

What exactly is the value when using jQuery's `.each()` method with the function accepting parameters for

Currently, I am diving into the world of jQuery with guidance from a fantastic book known as Head First jQuery. This book has made the learning process incredibly straightforward. The topic at hand is the .each() function, which I encountered in an image ...

``I am experiencing issues with the Ajax Loader Gif not functioning properly in both IE

I am brand new to using ajax and attempting to display a loading gif while my page loads. Interestingly, it works perfectly in Firefox, but I cannot get it to show up in Chrome or IE. I have a feeling that I am missing something simple. The code I am using ...

Implementing event handlers for each element by utilizing jQuery

Can you explain how I can effectively combine .on with .each? $('[id^="thing"]').each(???) For example, you can use: $("#button").on("click", function() { console.log(this.id) }) ...

Leveraging PHP to dynamically insert image file names into a directory for populating the HTML img src attribute in a Bootstrap

I am trying to dynamically populate a Bootstrap carousel with images from a folder by using PHP to scan the image files. However, instead of displaying the images in the carousel, only the names of the images are being listed. Below is my code, and I have ...