-1

I am trying to hide the header and stick the div to top(which is just below the header) when a user starts scrolling down a page.

  1. It should remain at the top till a user has reached 350px from top.
  2. When user scrolls upwards only the header should be shown and not the div below it.

I have tried with css( sticky and fixed position) but it is not giving the desired result.

Here's my fiddle

Here's the jquery(I am not good at it) that I tried(with the help of someone) but this is only 25% of what I am trying to achieve.

$(function(){
  $(window).scroll(function(e) {
    if($(this).scrollTop()>300){
      $('.header').fadeOut(); // Fading in the button on scroll after 300px
    }
    else{
      $('.header').fadeIn(); // Fading out the button on scroll if less than 300px
    }
  });
});
Rahul
  • 493
  • 6
  • 27

2 Answers2

0

Cant do this purly with css. Check jquerys Scroll event, possible soloution

$(window).scroll(function(e){ 
  var $el = $('.fixedElement'); 
  var isPositionFixed = ($el.css('position') == 'fixed');
  if ($(this).scrollTop() > 200 && !isPositionFixed){ 
    $('.fixedElement').css({'position': 'fixed', 'top': '0px'}); 
  }
  if ($(this).scrollTop() < 200 && isPositionFixed)
  {
    $('.fixedElement').css({'position': 'static', 'top': '0px'}); 
  } 
});

Added a link in the comments for full soloution.

ThunD3eR
  • 3,216
  • 5
  • 50
  • 94
  • No it doesn't solve my purpose and it could also have been done with css alone(position:sticky ) – Rahul Jul 18 '17 at 12:20
  • From what you are trying to do psotion:sticky would not cover all aspects. Position:sticky only positions a certain element but the logic you are describing has to be triggered with an event, hence why i recommend the scroll event. I would recommed you try it. – ThunD3eR Jul 18 '17 at 12:42
  • Soloution can alos be found here: https://stackoverflow.com/questions/1216114/how-can-i-make-a-div-stick-to-the-top-of-the-screen-once-its-been-scrolled-to – ThunD3eR Jul 18 '17 at 14:02
0

You'll need to set your header and .newswrap to position: fixed. Then this will work.

$(document).ready(function(){
    $(window).scroll(function() {
        if($(window).scrollTop() < 350) {
            $("header").show();
            $(".newswrap").hide();
        } else {
            $("header").hide();
            $(".newswrap").show();
        }
    });
});
Nicholas
  • 115
  • 6