Continue scrolling once you reach the fixed-positioned div

live demo

html

<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>

css

.container{  
    margin: 0;
    padding: 0;
    margin-top: 101px;    
}
div{
    height: 100px;
    width: 100%;
}
.one{
    background: red;
    position: fixed;
    top: 0;
}
.two{
    background: green;
}
.three{
    background: blue;
    height: 500px;
}
.four{
    background: black;
}

Question:

How can I make the green div scroll normally without being hidden inside the red div, while keeping the blue div and all subsequent divs visible when scrolling?

Is there a way to achieve this using jQuery or pure CSS?

Attempted jQuery solution:

I tried the following code but it's not working as expected. Can you please suggest a better approach?

$(window).scroll(function(){
   var topHeight = 200;
    var scrollHeight = $(window).scrollTop();
    var totalHeight = $('.three').height() + $('.four').height();
    if (scrollHeight == topHeight){
        $('body').css('margin-top',totalHeight);
    }
});

Answer №1

Just a little bit more to go - add position: relative to the CSS styling of div.three

.three{
    background: blue;
    height: 500px;
    position: relative;
}

Also, remember to apply this to other non-scrolling divs like div.four, and so on.

Check out the working example on jsFiddle: http://jsfiddle.net/damoiser/nUwJa/1/

Answer №2

Here is a JavaScript function that you can use to make an element follow the user as they scroll down the page. Check out the demo here

var windw = this;
$.fn.followTo = function ( pos ) {
    var $this = this,
        $window = $(windw);

    $window.scroll(function(e){
        if ($window.scrollTop() > pos) {
            $('.one').css({
                position: 'absolute',
                top: pos
            });
        } else {
            $('.one').css({
                position: 'fixed',
                top: 0
            });
        }
    });
};

$('.one').followTo(100);

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

Display the datepicker beneath the input field

I successfully integrated the datepicker, but I prefer for the calendar to display below the date input field rather than above it. HTML5 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv=" ...

Learn the steps to update PHP headers on a specific website using AJAX

contactfrm.php <?php // Server side validation $name = $_POST['name']; $surname = $_POST['surname']; $bsubject = $_POST['subject']; $email= $_POST['email']; $message= $_POST['message']; $to = " ...

Mobile navigation bar with Bootstrap transparency

I recently encountered a challenge with my Bootstrap navbar where I needed to remove the background. To achieve this, I applied the class "navbar-fixed-top" to the main wrapper. <nav class="navbar navbar-fixed-top"> After making this change, the na ...

Trouble getting custom CSS media queries to function properly alongside Bootstrap 3

I've encountered an issue while using bootstrap 3 with jquery UI to implement search and select fields for the user. The CSS code seems to be working fine on larger screens, but it's completely non-functional on smaller screens. I tried applying ...

I am looking to navigate between tabs on a multi-part form in order to submit all the form data

My current form consists of five questions, each on a separate tab. What I am trying to achieve is the following: When the user submits the form data on the fifth tab An Ajax request sends the form data to a background script for processing Simultaneousl ...

Combine jQuery and CSS to create a scrollable and extended fixed header

I am experiencing an issue where the header is fixed when scrolled down, but when I scroll back up to the top, it detaches and becomes unfixed again. How can I make the header stay fixed for a prolonged period of time? Are there any specific adjustments I ...

What about a lightbox with enhanced jQuery features?

As a newcomer to jQuery, I've never experimented with lightboxes before. However, I was tasked with creating something fun for April Fools' Day at work. Naively, I accepted the challenge thinking it would be simple, but now I find myself struggli ...

Creating randomized sequences using JavaScript

One of my hobbies involves organizing an online ice hockey game league where teams from different conferences compete. It's important to me that every team gets an equal number of home and away matches throughout the season. To simplify this task, I&a ...

Converting Greek text to UTF-8 using Javascript

Currently, I am working on a project with my teacher to digitalize a Greek textbook by transforming it into an online application. This process involves the conversion of a Shapefile, which draws polygons on maps along with polygon descriptions, and mappin ...

What steps can I take to ensure that a user only clicks on my voting link once for a specific post?

I am managing a MySQL database with two tables. One table is named 'users' with the column 'uname' as the primary key, which stores usernames as strings. The second table is named 'posts' with the column 'id' as the ...

Show a particular attribute from an array

My goal is to create a function that displays only minivans from an array of cars when a button is pressed. However, I'm having trouble getting anything to display when the button is clicked, even though there are no errors in the program. Any advice ...

Performing an AJAX request using jQuery without specifying the method name in the URL

Is the Page_Load method called if only the page name is specified in the AJAX call URL? $.ajax({ type: "POST", url: "PageName.aspx", //No method name data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: fu ...

The height of the ReactPlayer dynamically adjusts to accommodate content beyond the boundaries of the page

I have a video on my webpage that I want to take up the entire screen, but currently, users have to scroll a bit to reach the bottom, which is not ideal. This is my JavaScript: <div id="page"> <div id="video-container"> ...

Slight Misalignment of Elements

I am attempting to align two corners of an element so that they perfectly match the corners of another element. In simpler terms, I am aiming to synchronize the corners of one element with those of another element. Below is the code snippet: ... When y ...

Ajax displays JSON data within an array format

Looking for a solution where I have MySQL data displayed in a table, with each row having a button. When the button is clicked, a bootstrap modal should appear containing that data. I have converted the MySQL data to JSON format and assigned the ".view_dat ...

Is it possible to modify the value of a non-HTML attribute in an input field using jQuery?

I have a text input field that looks like this: <input type="text" value="" somethingSpecial="filename.txt" id="myID" class="box"> There is also a select list as shown below: <select name="type" class="form-select" id="type"> <option ...

Requesting a download of a file via an Ajax call from a RESTful service

I'm still getting the hang of AJAX. I've set up a request to send to the server using AJAX, and the service returns a text file. However, when the data is returned, no download box pops up. Here's the REST service that sends back the file: ...

Tips for centering an image vertically in a table's cell

I'm looking to vertically center the text, but I'm not sure how to do it. Check out my attempt on the fiddle link below: http://jsfiddle.net/jTW4d/ ...

Having trouble with PHP when using JQuery Ajax to post data

Currently, I am working with a list of records retrieved from a MySQL table. Each record has been assigned an onclick function to pass data for further database queries without having to refresh the page. <a href='javascript:void(0)' onclick= ...

Updating a property on an object during iteration

Currently, I am in the process of developing a Single Page Application using Laravel on the backend and Vue.js. I have two arrays that are crucial to my project: The first array is accessArray: ["BIU","CEO","Finance","HRD","Group"] The second array is a ...