2

Suppose I have headings like below

<h1 class="fixontop">heading 1</h1>
content goes here.
.
.
.
long paragraph.
<h1 class="fixontop">heading 2</h1>
2nd content goes here.
.
.
.
long paragraph.
<h1 class="fixontop">heading 3</h1>
3nd content goes here.
.
.
.
long paragraph.

So When I scroll Heading 1 should be fixed on top and I scroll down heading 2 should be fixed and all other headings fixed position must be removed.I think it is only possible via jquery.How can i do it ?

I have tried below..

 $(window).scroll(function() {
    if ($(this).scrollTop() ) { //Here some condition which finds if the heading tag is in screenview.  
        $('.fixontop').css({
            'display': 'fixed'
        });
    }
});

Here is fiddle http://jsfiddle.net/0can8pt9/

Vishnu
  • 2,372
  • 6
  • 36
  • 58
  • Try using `.each()` to target the `.fixontop` classes of each element. – dingo_d Jun 20 '15 at 08:46
  • possible duplicate of [Freeze Header until Irrelevant (HTML, CSS and JS)](http://stackoverflow.com/questions/7385068/freeze-header-until-irrelevant-html-css-and-js) – jcuenod Jun 20 '15 at 09:09

1 Answers1

0

check this one out https://jsfiddle.net/ctjdpe91/1/ i think using plugin like waypoints for such purposes is a good idea

var scrollTimeout;
var breakpoints = [];

function fix_heading(heading){
    if( heading.hasClass('heading-fixed'))
        return 

    heading
        .addClass('heading-fixed')
         // prevent content jumping
        .parents('section').css('padding-top', heading.height())
}

function unfix_heading(heading){
    if(! heading.hasClass('heading-fixed'))
        return

    heading
        .removeClass('heading-fixed')
        .parents('section').css('padding-top', 0);    
}

function fix_headings(breakpoints){
    clearTimeout(scrollTimeout);
    scrollTimeout = setTimeout(function(){
        $(breakpoints).each(function(){
            var breakpoint = this;
            var breakpoint_heading = $('.fixontop[data-fix-on='+breakpoint+']')

            if(document.body.scrollTop > breakpoint ){
                fix_heading(breakpoint_heading)
            }

            if(document.body.scrollTop < ( breakpoint )){
                unfix_heading(breakpoint_heading)
            }

            //scrolled out of parent container
            if(document.body.scrollTop > (breakpoint + breakpoint_heading.parents('section').outerHeight())){
                unfix_heading(breakpoint_heading)   
            }

         })
     }, 30) //timeout here for better performance
}

$(function(){
    //setup breakpoints
    $('.fixontop').each(function(){
        breakpoints.push ($(this).position().top)
        $(this).attr('data-fix-on', $(this).position().top)
    })
    $(document).scroll(function(){fix_headings(breakpoints)})
})
Robert Isaev
  • 121
  • 5