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

How to Make a Fixed Div Scroll Horizontally with Page Content using jQuery?

Barbara Streisand
Release: 2024-10-27 20:58:30
Original
565 people have browsed it

How to Make a Fixed Div Scroll Horizontally with Page Content using jQuery?

Horizontally Scrolling Fixed Divs with jQuery

In this problem, we have a div element with a fixed vertical position using jQuery and CSS. However, horizontal scrolling causes conflicts with content to the right of the div. We aim to enable horizontal scrolling for the div along with the page content.

The solution involves maintaining the fixed position for the element, but additionally manipulating its left property using jQuery:

<code class="javascript">var leftInit = $(".scroll_fixed").offset().left;
var top = $('.scroll_fixed').offset().top - parseFloat($('.scroll_fixed').css('margin-top').replace(/auto/, 0));

$(window).scroll(function(event) {
    var x = 0 - $(this).scrollLeft();
    var y = $(this).scrollTop();

    // Vertical positioning logic
    if (y >= top) {
        $('.scroll_fixed').addClass('fixed');
    } else {
        $('.scroll_fixed').removeClass('fixed');
    }

    // Horizontal positioning
    $(".scroll_fixed").offset({
        left: x + leftInit
    });
});</code>
Copy after login

By using leftInit, we account for any possible left margin on the fixed element. This approach allows the fixed div to scroll horizontally along with the content, similar to the second example in the provided resource.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template