Snap element to top on scrolling 50px

Useful for search screen with results below it

by Sree K

HTML

<div style="position: fixed; z-index:999999; width:100%; background:rgba(44,62,80,0.8);" class="row">
  <div id="search">
      <div class="col-md-4 col-md-offset-4">
          <form method="post">
              <input type="text" id="search-query-3" placeholder="USPTO" class="form-control" name="search_data">
          </form>
      </div>
  </div>
</div>

<div class="sections">
  <section id="1"><h1>First</h1></section>
  <section id="2"><h1>Second</h1></section>
  <section id="3"><h1>Third</h1></section>
  <section id="4"><h1>Fourth</h1></section>
  <section id="5"><h1>Fifth</h1></section>
</div>
<footer></footer>

CSS

@import url(http://fonts.googleapis.com/css?family=Open+Sans);

#search {
    padding: 3% 0;
}

.nopadding{
    padding: 0;
}

.col-md-4{
    width: 33.3333%;
    float: left;
    min-height: 1px;
    padding-left: 15px;
    padding-right: 15px;
    position: relative;
}

.col-md-offset-4 {
    margin-left: 33.3333%;
}

footer {
  height: 500px;
  background: blue;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Open Sans', sans-serif;
}

/* Navigation */

nav {
  width: 100%;
  height: 60px; 
  position: fixed; 
  top: 0;
  background: #1ABC9C;
}

/* Headings */

h1 {
  font-size: 5rem;
  color: #34495E;
}

/* Sections */

section {
  width: 100%;
  padding: 50px;
  background: #fff;
  border-bottom: 1px solid #ccc;
  height: 500px;
  text-align: center;
}
section:nth-child(even) {
  background: #ecf0f1;
}
section:nth-child(odd) {
  background: #bdc3c7;
}

section.active {}

footer {
  height: 500px;
  background: #34495e;
}

JavaScript

$(document).on('scroll', function(){
    // compare original y position of element to y position of page
    if( $(window).scrollTop() > 50 ){ 

        // snap element to the top by changing css values of element
        $('#search').css('padding','0'); 

    }else{          

        // re-position to original flow of content
        $('#search').css('padding','3% 0'); // set to default         
    }               
})