user6465860
user6465860

Reputation:

How do I gradually change the color of navbar on scroll?

I have a transparent navbar which I would like to gradually change color until it is finally opaque as it passes below a div. I have this:

$(document).scroll(function() {
  var dHeight = $(this).height()-$(window).height();
  if (dHeight >= $(this).scrollTop()) {
    $('nav').css('background', 'rgba(53,145,204,' + $(this).scrollTop() / dHeight + ')');
  }
});
body {
  margin: 0;
}
nav {
  background: rgba(53, 145, 204, 0);
  position: fixed;
  top: 0;
  width: 100%;
}
nav ul > li {
  display: inline-block;
}
.container {
  height: 1000px;
  margin-top: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<nav>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
</nav>
<div class="container">
  <div>
    Scroll me...
  </div>
</div>

... so far but rather than taking the entire height of the page to become opaque I would like it to have become opaque after it reaches the bottom of a div, could anyone help me? Thanks in advance

Upvotes: 2

Views: 760

Answers (3)

Himesh Suthar
Himesh Suthar

Reputation: 562

Here I have fetched height of div. So, your nav will now become opaque at scroll you require.

Here I have attached fiddle. Hope this will help you.

jsfiddele

Upvotes: 1

Tirthraj Barot
Tirthraj Barot

Reputation: 2679

Yup. Certainly it can be done.. check this out.. it will make your opaque as soon as you have finished scrolling through your div with the text Scroll me ...

And kindly correct me if I have misinterpreted your question.

$(document).scroll(function() {
  var dHeight = $("#nav1").height();
  var alpha = (($(this).scrollTop() / dHeight ) / 10);
  $('#changeBg').css('background', 'rgba(53,145,204,' +(alpha * 2)  + ')');
});
body {
  margin: 0;
}
#changeBg{
  background: rgba(53, 145, 204, 0);
  position: fixed;
  top: 0;
  width: 100%;
}
nav ul > li {
  display: inline-block;
}
.container {
  height: 1000px;
  margin-top: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<nav id="changeBg">
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
</nav>
<div class="container">
  <div id="nav1">
    Scroll me...
  </div>
</div>

Upvotes: 0

Murali Krishna
Murali Krishna

Reputation: 141

Is this the one you expecting?

  • Item 1
  • Item 2
  • Item 3
Scroll me...

body {
  margin: 0;
}
nav {
  background: rgba(53, 145, 204, 0);
  position: fixed;
  top: 0;
  width: 100%;
}
nav ul > li {
  display: inline-block;
}
.container {
  height: 1000px;
  margin-top: 100px;
}

$(document).scroll(function() {
  var dHeight = $(this).height()-$(window).height();
  if (dHeight >= $(this).scrollTop()) {
    $('nav').css('background', 'rgba(53,145,204,' + $(this).scrollTop() + ')');
  }
});

Upvotes: 0

Related Questions