Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the background color with a sticky element

I would like to change the body color background on scroll with a sticky element.

body {
  margin: 0;
  background: lightblue;
}

.blue-container {
  height: 70vh;
}

.blue {
  height: 40vh;
  position: sticky;
  width: 70%;
  top: 0;
  background: blue;
  margin: auto;
}

.pink {
  height: 500px;
  position: relative;
  width: 70%;
  margin-right: auto;
  margin-left: auto;
  background: pink;
  text-align: center;
}
<div class='blue-container'>
  <div class='blue'></div>
</div>

<div class='pink'> When I touch the blue bloc, I would like the 'body background' change into an other color (for exemple : orange)</div>

Here's my jsFiddle to understand what I want.

like image 625
user9018937368 Avatar asked Oct 14 '25 18:10

user9018937368


1 Answers

You could calculate the empty space between blue div and pink div with a difference ($('.blue-container').height() - $('.blue').height()), then when the document scrolled till that misure you know that the pink div has touch the blue one.

$(function(){

  $(window).scroll(function(){
    var margin = $('.blue-container').height() - $('.blue').height();
    if($(this).scrollTop()>=margin){
        $("body").addClass("orange")
    } else{
    	$("body").removeClass("orange")
    }
  });
});
body {
  margin:0;
  background:lightblue;}

.blue-container {
 height:70vh;
}

.blue {
 height:40vh;
 position:sticky;
 width:70%;
 top:0;
 background:blue;
 margin:auto;
}

.pink {
 height:500px;
 position:relative;
 width:70%;
 margin-right:auto;
 margin-left:auto;
 background:pink;
  text-align:center;
}

.orange{
  background:orange
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='blue-container'>
  <div class='blue'></div>
</div>

<div class='pink'> When I touch the blue bloc, I would like the 'body background' change into an other color (for exemple : orange)</div>
like image 123
ReSedano Avatar answered Oct 17 '25 09:10

ReSedano