0

I need to create a banner's placeholder that needs to scroll up together with a page until it reaches a browser's top edge and then it should be fixed at the top. When the page is scrolled down, the banner also needs to scroll with the page again. I'm not sure whether I'm clear enough so you can see the example at Watch Critic. You'll notice that the banner in the right column behaves just like I've described.

I don't have experience with JavaScript so can this be achieved with HTML and CSS only?

user2567824
  • 1
  • 1
  • 1
  • 1

2 Answers2

0

Living example: http://jsfiddle.net/KXXhQ/

You need to make use of the scroll event of jQuery and then add a new class to your header in order to fix it:

jQuery

  //by default, the static menu is hidden
  var showStaticMenuBar = false;

  //when scrolling...
  $(window).scroll(function () {

      //if the static menu is not yet visible...
      if (showStaticMenuBar == false) {
          //if I scroll more than 200px, I show it 
          if ($(window).scrollTop() >= 200) {
              //showing the static menu
              $('#header').addClass('fixed');

              showStaticMenuBar = true;
          }
      }
      //if the static menu is already visible...
      else {
          if ($(window).scrollTop() < 200) {
              $('#header').removeClass('fixed');

              //I define it as hidden
              showStaticMenuBar = false;
          }
      }
  });

CSS

#header{
    display:block;
    width: 100%;
    height:50px;
    background: #ddff00;
}
#header.fixed{
    position:fixed; 
    top: 0;  /*fixing it at the top*/
    z-index: 999;  /* over any other element*/
}

Living example: http://jsfiddle.net/KXXhQ/

Alvaro
  • 40,778
  • 30
  • 164
  • 336
0

This is how you can set the position to be fixed in CSS. If you want to achieve more behaviors you can define them as CSS classes and when you need to change behavior just add and remove classes with jQuery.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175