michaelmcgurk
michaelmcgurk

Reputation: 6509

Change element when other element is visible with jQuery

I am currently working on some code involving persistent headers. Is it possible when my .floatingHeader is visible that I can make the original hidden?

Currently when I scroll the page, my code is:

<h2 class="persist-header">Some Other Area</h2>
<h2 class="persist-header floatingHeader" style="width: 545px; visibility: visible;">Some Other Area</h2>

but could I change this to:

<h2 class="persist-header" style="visibility: hidden">Some Other Area</h2>
<h2 class="persist-header floatingHeader" style="width: 545px; visibility: visible;">Some Other Area</h2>

Here is my Javascript:

function UpdateTableHeaders() {
    $(".persist-area").each(function() {
        var el = $(this),
            offset = el.offset(),
            scrollTop = $(window).scrollTop(),
            floatingHeader = $(".floatingHeader", this)

        if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
            floatingHeader.css({
                "visibility": "visible"
            });
        } else {
            floatingHeader.css({
                "visibility": "hidden"
            });
        };
    });
}

// DOM Ready
$(function() {
    var clonedHeaderRow;
    $(".persist-area").each(function() {
        clonedHeaderRow = $(".persist-header", this);
        clonedHeaderRow
            .before(clonedHeaderRow.clone())
            .css("width", clonedHeaderRow.width())
            .addClass("floatingHeader");
        });

    $(window)
        .scroll(UpdateTableHeaders)
        .trigger("scroll");
});

Here is the Demo: http://jsfiddle.net/j5z5tdjy/

Upvotes: 0

Views: 97

Answers (1)

Devjit
Devjit

Reputation: 375

Try This.

       if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
           floatingHeader.css({
            "visibility": "visible"
           });
           floatingHeader.prev().css({"visibility":"hidden"});
       } else {
           //$(".persist-header").css({"visibility":"visible"});
           floatingHeader.css({
            "visibility": "hidden"
           });
           floatingHeader.prev().css({"visibility":"visible"});
       };

fiddle: http://jsfiddle.net/j5z5tdjy/4/

Upvotes: 2

Related Questions