zrna
zrna

Reputation: 594

Fade Out only background image not the text

I'm trying to fade an image as background an I want to fade out only background image not the text. I want to text stay on the page. This is what I use:

https://codepen.io/nickcil/pen/sfutl

Help me please.

$(window).scroll(function(){
    $(".top").css("opacity", 1 - $(window).scrollTop() / 250);
  });

/*win.scroll(function(){
  scrollPosition = win.scrollTop();
  scrollRatio = 1 - scrollPosition / 300;
  $(".top").css("opacity", scrollRatio);
*/

/*$(window).scroll(function(){
    var scrollVar = $(window).scrollTop();
    $('.top').css("opacity", 1 - scrollVar/300);
})*/
body {
  margin: 0;
  height: 1000px;
}

.top {
  margin: 0;
  position: relative;
  width: 100%;
  background-color: #aaa;
  height: 300px;
  opacity: 1;
  text-align: center;
  font-family: 'helvetica';
  font-size: 80px;
  font-weight: 100;
  color: #fff;
}

.title {
  position: absolute;
  top: 60%;
  left: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top">
  <div class="title">Fade Away</div>
</div>

Upvotes: 1

Views: 701

Answers (2)

Ehsan
Ehsan

Reputation: 12959

opacity affects all content inside an element,you must use background-color instead of opacity, so:

Change:

$(".top").css("opacity", 1 - $(window).scrollTop() / 250);

To:

$(".top").css('background-color', 'rgba(170,170,170,' + (1 - ($(window).scrollTop() / 250)) + ')');

$(window).scroll(function(){
  $(".top").css('background-color', 'rgba(170,170,170,' + (1 - ($(window).scrollTop() / 250)) + ')');
});
body {
  margin: 0;
  height: 1000px;
}

.top {
  margin: 0;
  position: relative;
  width: 100%;
  background-color: #aaa;
  height: 300px;
  opacity: 1;
  text-align: center;
  font-family: 'helvetica';
  font-size: 80px;
  font-weight: 100;
  color: #fff;
}

.title {
  position: absolute;
  top: 60%;
  left: 100px;
  color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top"><div class="title">Fade Away</div></div>

Note: I change color for .title to black,for you to see the result better.

Upvotes: 1

delinear
delinear

Reputation: 2795

You need to add another element inside .top and have that fade out instead of fading the outer container:

$(window).scroll(function(){
    $(".top-inner").css("opacity", 1 - $(window).scrollTop() / 250);
  });
body {
  margin: 0;
  height: 1000px;
}

.top-inner {
  margin: 0;
  position: relative;
  width: 100%;
  background-color: #aaa;
  height: 300px;
  opacity: 1;
  text-align: center;
}

.title {
  position: absolute;
  top: 60%;
  left: 100px;
  font-family: 'helvetica';
  font-size: 80px;
  font-weight: 100;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top">
  <div class="top-inner"></div>
  <div class="title">Fade Away</div>
</div>

Upvotes: 0

Related Questions