Taqasar Walayat
Taqasar Walayat

Reputation: 45

Fade in when scroll down and fade out when scroll up

This is the css code of the fade in animation

.searchbar {
  opacity: 0;
}

.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}

@-webkit-keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.fadeIn {
  -webkit-animation-name: fadeIn;
  animation-name: fadeIn;
}

I want that a searchbar fades in when I scroll down (after 700px) and when I scroll up (so its less than 700px) it fades out

this is the script in js

$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  if (scroll >= 700) {
    $(".searchbar").addClass("animated_fi fadeIn");
  } else {
    $(".searchbar").removeClass("animated_fi fadeIn");
  }
});

Upvotes: 2

Views: 3127

Answers (1)

billy.farroll
billy.farroll

Reputation: 1921

If I'm understanding your query correctly. You're after something like this:

$(window).scroll(function(e) {
  if ($(this).scrollTop() > 300) { // choose the value you want.
    $('#menu:hidden').slideDown();
  } else {
    $('#menu:visible').slideUp();
  }
});
body {
  height: 2000px;
  margin: 0;
  background-color: black;
}

#menu {
  background: white;
  color: black;
  padding: 1em;
  width: 100%;
  display: none;
  position: fixed;
  top: 0;
}

h1 {
  font-family: 'Lato', sans-serif;
}

.search-container {
  width: 490px;
  display: block;
  margin: 0 auto;
}

input#search-bar {
  margin: 0 auto;
  width: 100%;
  height: 45px;
  padding: 0 20px;
  font-size: 1rem;
  border: 1px solid #d0cfce;
  outline: none;
}

input#search-bar:focus {
  border: 1px solid #008abf;
  transition: 0.35s ease;
  color: #008abf;
}

input#search-bar:focus::-webkit-input-placeholder {
  transition: opacity 0.45s ease;
  opacity: 0;
}

input#search-bar:focus::-moz-placeholder {
  transition: opacity 0.45s ease;
  opacity: 0;
}

input#search-bar:focus:-ms-placeholder {
  transition: opacity 0.45s ease;
  opacity: 0;
}

.search-icon {
  position: relative;
  float: right;
  width: 75px;
  height: 75px;
  top: -62px;
  right: -45px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>

  <div id="menu">
    <center>
      <h1>Hello</h1>
    </center>
    <form class="search-container">
      <input type="text" id="search-bar" placeholder="What can I help you with today?">
      <a href="#"><img class="search-icon" src="http://www.endlessicons.com/wp-content/uploads/2012/12/search-icon.png"></a>
    </form>
  </div>

  <center>
    <div>
      <h1 style="color: white;">Scroll Down</h1>
    </div>
  </center>

</body>

This will fade a search bar in when the user scrolls, and then fade out when they scroll back. If you want the effect to take place at 700px just change the JQuery 300 -> 700.

Upvotes: 2

Related Questions