Replacing a header with a fixed position with a fixed position of the header

So I have a node.js application using an expression and trying to do the following:

div(class="title")
  h1(class="h1_title") example_title

      

My jQuery for this looks like this:

jQuery(function($) {
    function fixDiv() {
      var $cache = $('.title');
      if ($(window).scrollTop() > 140)
        $cache.css({'position': 'fixed', 'top': '10px'});
      else
        $cache.css({'position': 'relative', 'top': 'auto'});
    }
    $(window).scroll(fixDiv);
    fixDiv();
});

      

So when I scroll the header it will be fixed to the top of the page. However, it works! I have another title below this, the same code. But I am trying to get my title to replace the previous one and become fixed.

So, since you scroll through the content, the title is always captured, but it is simply updated by the title relative to the content of your view.

Can anyone help, I would really appreciate it. I can't find anything exactly what I'm looking for and my knowledge is limited. Thank!

+3


source to share


2 answers


I see you asked a lot of questions about this ... I'll show you an example that might help.

With a structure like this:

<div class="title">TITLE</div>
<div class="cont"><h1>TITLE</h1></div>
<div class="cont"><h1>Content1</h1></div>
<div class="cont"><h1>Content2</h1></div>
<div class="cont"><h1>Content3</h1></div> 

      



Where there .title

will be a fixed header, you can use Jquery to change the base of values ​​in h1

other containers.

$(window).scroll(function(){
  $('.cont').each(function(){
    var t = $(this).offset().top - 50,
        tit = $(this).find('h1').text(),
        h = $(this).height(),
        ws = $(window).scrollTop();
    if (t < ws && ws < (h+t)) {
         $('.title').html(tit);
    } 
  })
})

      

Check out the CodePen Demo

+1


source


Here's a really basic example: http://jsfiddle.net/jgxevwa6/1/ - I haven't tried to achieve perfect spacing or anything.

You have your fixed class:

.fixed {
    position: fixed;
    top: 0;
}

      



And then the magic. Basically, every time you scroll, it loops through each block and determines what's in the viewport using the basic scrolling model:

(function($) { 
    var utils = {
        fixTitle: function(e) {
            var top = e.currentTarget.scrollY;

            $('div').each(function() {
                var thistop = $(this).position().top;
                if(top > thistop) {
                    $('.title').removeClass('fixed');
                    $(this).find('.title').addClass('fixed');
                }
            });
        }
    };

    $(function() {
        $(window).scroll(utils.fixTitle);    
    });
})(jQuery);

      

javascript and CSS might be a little more precise, but that gives you the basic gist.

+1


source







All Articles