Home >Web Front-end >CSS Tutorial >How to Make a Fixed Position Div Scroll Horizontally with Content Using jQuery?

How to Make a Fixed Position Div Scroll Horizontally with Content Using jQuery?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 09:30:30514browse

How to Make a Fixed Position Div Scroll Horizontally with Content Using jQuery?

Horizontal Scrolling of a Fixed Position Div Using jQuery

In this article, we'll address the issue of horizontal content scrolling within a fixed position div using jQuery.

A user has a div with a class scroll_fixed and wants to fix it when it reaches the top of the page. The following CSS styles the div:

.scroll_fixed {
    position:absolute
    top:210px
}
.scroll_fixed.fixed {
    position:fixed;
    top:0;
}

jQuery code is used to add a fixed class when the div reaches the top:

$(window).scroll(function (event) {
    // Check if the scroll position is greater than the top offset of the div
    if ($(this).scrollTop() >= top) {
        $('.scroll_fixed').addClass('fixed');
    } else {
        $('.scroll_fixed').removeClass('fixed');
    }
});

This works well for vertical scrolling, but causes a conflict with content to the right of the div when the browser window is small. The user wants the div to scroll horizontally with the content.

/Solution:

To make the div scroll horizontally, we need to keep its position:fixed and manipulate the left property instead of the top. The following updated jQuery code accomplishes this:

var leftInit = $(".scroll_fixed").offset().left;

$(window).scroll(function (event) {
    // Get the current scroll positions
    var x = 0 - $(this).scrollLeft();
    var y = $(this).scrollTop();

    // Fix the div when it reaches the top
    if (y >= top) {
        $('.scroll_fixed').addClass('fixed');
    } else {
        $('.scroll_fixed').removeClass('fixed');
    }

    // Adjust the left offset of the div based on the scroll position
    $(".scroll_fixed").offset({
        left: x + leftInit
    });
});

By using leftInit, we account for any left margin on the div. Try this solution at: http://jsfiddle.net/F7Bme/

The above is the detailed content of How to Make a Fixed Position Div Scroll Horizontally with Content Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn