Thsise Faek
Thsise Faek

Reputation: 311

Change color when user has scrolled down enough and then back

I have several divs arranged vertically one on top of the other which from here on out I will call panels. Each panel has the width and height of the viewport. All panels have the same background color at all times. Initially, that color is black.

Every other panel is empty, and acts as a gap between panels that actually have content. The order is like this:

  1. Content
  2. No content
  3. Content
  4. No content
  5. Content

What I want to do is make it so that when a user has scrolled down enough for a panel with content to be out of view, the color should change from black to white. Then, once they have scrolled far enough for the second panel with content to be out of view, it should change back.

This is the part I cannot figure out. I have a working demo with my code so far:

$(document).scroll(function() {

  var viewportHeight = $("html").outerHeight();
  var currentY = $(document).scrollTop();
  if (currentY % viewportHeight != 0) {
    lighten();
  } else {
    darken();
  }
});

function darken() {
  $("body").css("background-color", "black");
  $(".panel.content").css("color", "white");
}

function lighten() {
  $("body").css("background-color", "white");
  $(".panel.content").css("color", "black");
}
html,
body,
.panel {
  width: 100%;
  height: 100%;
}

body {
  background-color: black;
  overflow-y: visible;
  overflow-x: hidden;
  transition: background-color 500ms linear;
}

.panel {
  border: 2px solid red;
}

.content {
  color: white;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<body>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
  <div class="panel blank">
  </div>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
  <div class="panel blank">
  </div>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
</body>

As you can see, my code is a ways off from achieving the desired result. Not only is the order wrong, the main problem is that it only triggers when the user is at the exact Y for the change to happen.

The order should be:

  1. Black
  2. White
  3. White
  4. Black
  5. Black
  6. White
  7. White
  8. Black
  9. Black

etc.

How do I do this?

Upvotes: 4

Views: 312

Answers (7)

NoOorZ24
NoOorZ24

Reputation: 3222

I know it's a bit late, but I made a solution for this and didn't had time to post it.

So: "How is my solution any different?"

I get gap-from-top values to all your .blank divs and then check where view-port is located. This allows you to use borders, add any other divs in between, change size of your divs and this will not lose functionality.

var elem = document.getElementsByClassName("blank");
var i;
var marks = [];
for (i = 0; i < elem.length; i++) {
  var rect = elem[i].getBoundingClientRect();
  marks.push(rect.top);
}

$(document).scroll(function() {
  if (findi() % 2 == 1) {
    lighten();
  } else {
    darken();
  }
});

function findi() {
  pos = 0;
  for (i = 0; i < marks.length; i++) {
    if (marks[i] < $(document).scrollTop()) {
      pos++;
    }
  }
  return (pos);
}

function darken() {
  $("body").css("background-color", "black");
  $(".panel.content").css("color", "white");
}

function lighten() {
  $("body").css("background-color", "white");
  $(".panel.content").css("color", "black");
}
body {
  background-color: black;
  overflow-y: visible;
  overflow-x: hidden;
  transition: background-color 500ms linear;
}

html,
body {
  padding: 0;
  margin: 0;
}

html,
body,
.panel {
  width: 100%;
  height: 100%;
}

.panel {
  border-bottom: 32px solid red;
}

.content {
  color: white;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel content">
  <h2> CONTENT </h2>
</div>
<div class="panel blank">
</div>
<div class="panel content">
  <h2> CONTENT </h2>
</div>
<div class="panel blank">
</div>
<div class="panel content">
  <h2> CONTENT </h2>
</div>
<div class="panel blank">
</div>
<div class="panel content">
  <h2> CONTENT </h2>
</div>
<div class="panel blank">
</div>
<div class="panel content">
  <h2> CONTENT </h2>
</div>
<div class="panel blank">
</div>
<div class="panel content">
  <h2> CONTENT </h2>
</div>
<div class="panel blank">
</div>
<div class="panel content">
  <h2> CONTENT </h2>
</div>
<div class="panel blank">
</div>
<div class="panel content">
  <h2> CONTENT </h2>
</div>
<div class="panel blank">
</div>
<div class="panel content">
  <h2> CONTENT </h2>
</div>

Upvotes: 2

Durgpal Singh
Durgpal Singh

Reputation: 11953

Add a condition in your code

Math.floor(currentY / viewportHeight) % 4 == 1 || Math.floor(currentY / viewportHeight) % 4 == 2

and your code is working now.

Testing

If you run this code in java it will display same output as you expected.

public static void main(String...arr){
    for(int i = 0; i<100; i++){
        if(i%4 ==1 || i%4 == 2){
            System.out.println("true");
        } else {
            System.out.println("false");
        }
    }
}

$(document).scroll(function() {

      var viewportHeight = $("html").outerHeight();
      var currentY = $(document).scrollTop();
      
      if (Math.floor(currentY / viewportHeight) % 4 == 1 || Math.floor(currentY / viewportHeight) % 4 == 2) {
        lighten();
      } else {
        darken();
      }
    });
    
    function darken() {
      $("body").css("background-color", "black");
      $(".panel.content").css("color", "white");
    }

    function lighten() {
      $("body").css("background-color", "white");
      $(".panel.content").css("color", "black");
    }
  html,
    body,
    .panel {
      width: 100%;
      height: 100%;
    }

    body {
      background-color: black;
      overflow-y: visible;
      overflow-x: hidden;
      transition: background-color 500ms linear;
    }

    .panel {
      border: 2px solid red;
    }

    .content {
      color: white;
      text-align: center;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
      <div class="panel content">
        <h2> CONTENT </h2>
      </div>
      <div class="panel blank">
      </div>
      <div class="panel content">
        <h2> CONTENT </h2>
      </div>
      <div class="panel blank">
      </div>
      <div class="panel content">
        <h2> CONTENT </h2>
      </div>
    </body>

Upvotes: 1

amitdigga
amitdigga

Reputation: 7158

$(document).scroll(function() {

  var viewportHeight = $("html").outerHeight();
  var currentY = $(document).scrollTop();
  var panelNumber = Math.floor(currentY / viewportHeight);
  if (panelNumber % 4 === 1 || panelNumber % 4 === 2) {
    lighten();
  } else {
    darken();
  }
});

function darken() {
  $("body").css("background-color", "black");
  $(".panel.content").css("color", "white");
}

function lighten() {
  $("body").css("background-color", "white");
  $(".panel.content").css("color", "black");
}
html,
body,
.panel {
  width: 100%;
  height: 100%;
}

body {
  background-color: black;
  overflow-y: visible;
  overflow-x: hidden;
  transition: background-color 500ms linear;
}

.panel {
  border: 2px solid red;
}

.content {
  color: white;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
  <div class="panel blank">
  </div>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
  <div class="panel blank">
  </div>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
  <div class="panel blank">
  </div>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
  <div class="panel blank">
  </div>
</body>

Not only is the order wrong, the main problem is that it only triggers when the user is at the exact Y for the change to happen.

yes..that is right. currentY % viewportHeight != 0 will not work. Scrolling is not smooth. Pulling scrollbar down may result in change of 10000 px/sec, but browser renders 60fps which means your currentY (scroll-y) will increase by 150px every frame (your are expecting a change of 1px). So if your code contains if(currentY === 100){} definitely not going to work. currentY may have values like 0,50,80,99,120,....

It should be clear currentY % viewportHeight != x is not so much different.

So if(0<currentY<500) will be be better option.

Now suppose viewportHeight = 500. We can get panelNumber = Math.floor(currentY/viewportHeight) (=>0,1,2,3,4,5...)

(Not clear from your question) Suppose you want to have panel: 0 =>black, 1=>white, 2=>white, 3=>black, 4=>black ... you can get black by panelNumber%4==0 || panelNumber%4==3.

[please change accordingly if you want something different]

Upvotes: 2

steliosbl
steliosbl

Reputation: 8921

Here is my solution. I'm pretty sure this is the order you need.

(function() {
    var lastfunc = darken;
    $(document).scroll(function() {
        var y = $(document).scrollTop();
        var x = $("html").outerHeight();
        var func = (Math.floor(((y + x) / (2 * x))) % 2) ? lighten : darken;
        if (func !== lastfunc) {
            lastfunc = func;
            func();
        }
    });
})();

This does the following:

  1. Create a variable lastfunc to keep track of the last thing we called.
  2. Get the user's Y and the height of the viewport.
  3. Use evil factorized math to get a bool which decides which of the two functions, lighten() or darken() to assign to func.
  4. Check to see if lastfunc is equal to func, to see if a change is necessary.
    • If they are not equal, call func() and set lastfunc equal to func

This has the following benefits:

  1. All wrapped up to prevent making lastfunc a global.
  2. Math is solid.
  3. This calls the style modifying functions only if a change is required.

I've also optimized your darken() and lighten() functions:

function darken() {
    document.body.style.backgroundColor = "black";
    $(".panel.content").css("color", "white");
}

function lighten() {
    document.body.style.backgroundColor = "white";
    $(".panel.content").css("color", "white");
}

This slight optimization saves jQuery the trouble of finding your body, which should save off a couple of milliseconds. Not a huge difference, but this is optimal.

Additional note: if you are able to get rid of the second style change in lighten and darken, we can get rid of the overhead of having the function calls at all, and do it all within scroll():

(function() { 
    var lastColor;
    $(document).scroll(function() {
        var y = $(document).scrollTop();
        var color = (Math.floor(((y + x) / (2 * x))) % 2) ? "red" : "blue";
        if (color !== lastColor) {
            lastColor = color;
            document.body.style.color = color;
        }
    });
})();

Demo of the first solution:

(function() {
    var lastfunc = darken;
    $(document).scroll(function() {
        var y = $(document).scrollTop();
        var x = $("html").outerHeight();
        var func = (Math.floor(((y + x) / (2 * x))) % 2) ? lighten : darken;
        if (func !== lastfunc) {
            lastfunc = func;
            func();
        }
    });
})();

function darken() {
    document.body.style.backgroundColor = "black";
    $(".panel.content").css("color", "white");
}

function lighten() {
    document.body.style.backgroundColor = "white";
    $(".panel.content").css("color", "white");
}
html,
body,
.panel {
  width: 100%;
  height: 100%;
}

body {
  background-color: black;
  overflow-y: visible;
  overflow-x: hidden;
  transition: background-color 500ms linear;
}

.panel {
  border: 2px solid red;
}

.content {
  color: white;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<body>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
  <div class="panel blank">
  </div>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
  <div class="panel blank">
  </div>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
</body>

Upvotes: 0

Manuel Otto
Manuel Otto

Reputation: 6540

I've made it so you can choose which panel sets the background color to white/black. You can do that by adding the class 'black' or 'white' to it, though the way you requested it makes perfect sense afterall. Also my solution uses a class to change the background color of the body. This should make it more easy to make style changes.

$(document).ready(init)

function init(){
	$(document).scroll(updateBackground)
	updateBackground()
}

function updateBackground(){
	var w = $(window).width()
	var h = $(window).height()
	var panels = $('.panel') // get all panels on page

	for(var i=0;i<panels.length;i++){ // loop though each panel
		var panel = panels.eq(i) // get the current panel
		var panel_y = panel.offset().top - $(document).scrollTop() // get the panels y coordinate relative to the window
		var panel_height = panel.height() // get the panels height
		if(panel_y<=0 && panel_y+panel_height>0){ // check if the panel is in the visible area
			if(panel.hasClass('black')){ // check if the panel is set to make the background black
				$('body').removeClass('white')
				$('body').addClass('black')
			}else if(panel.hasClass('white')){
				$('body').removeClass('black')
				$('body').addClass('white')
			}
			return // return, because we already found the visible panel
		}
	}
}
html{
  height: 100%
}
body{
	margin: 0;
	padding: 0;
	transition: background-color 500ms linear;
  height: 100%
}
body.white{
	background-color: white;
	color: black;
}
body.black{
	background-color: black;
	color: white;
}
.panel{
	width: 100%;
	height: 100%;
	box-sizing: border-box;
	padding: 50px;
	border: solid 1px #888888;
	text-align: center;
	overflow: hidden;
}
.panel > h1{
	font-size: 38pt;
} 
.panel > p{
	font-size: 18pt;
	line-height: 200%;
} 
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head
<body>

<div class="panel with-content black">
	<h1>Content</h1>
	<p>
	    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
	</p>
</div>

<div class="panel gap white"></div>

<div class="panel with-content white">
	<h1>Content</h1>
	<p>
	    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
	</p>
</div>

<div class="panel gap black"></div>

<div class="panel with-content black">
	<h1>Content</h1>
	<p>
	    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
	</p>
</div>

<div class="panel gap white"></div>

<div class="panel with-content white">
	<h1>Content</h1>
	<p>
	    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
	</p>
</div>

<div class="panel gap black"></div>

<div class="panel with-content black">
	<h1>Content</h1>
	<p>
	    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
	</p>
</div>

</body>
</html>

Upvotes: 1

Bhavin Solanki
Bhavin Solanki

Reputation: 4818

You can use .hover() on $(document).ready(); I have added an example of it if it works for you.

$(document).ready(function() {

  $(".panel.content").hover(function(){
       $("body").css("background-color", "white");
       $(this).css("color", "black");
  },function(){
       $("body").css("background-color", "black");
       $(this).css("color", "white");
  });
  
});

$(document).scroll(function() {

  $(".panel.content").hover(function(){
       $("body").css("background-color", "white");
       $(this).css("color", "black");
  },function(){
       $("body").css("background-color", "black");
       $(this).css("color", "white");
  });
  
});
html,
body,
.panel {
  width: 100%;
  height: 100%;
}

body {
  background-color: black;
  overflow-y: visible;
  overflow-x: hidden;
  transition: background-color 500ms linear;
}

.panel {
  border: 2px solid red;
}

.content {
  color: white;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<body>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
  <div class="panel blank">
  </div>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
  <div class="panel blank">
  </div>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
</body>

Upvotes: 1

31piy
31piy

Reputation: 23859

What I want to do is make it so that when a user has scrolled down enough for a panel with content to be out of view, the color should change from black to white. Then, once they have scrolled far enough for the second panel with content to be out of view, it should change back.

This statement conflicts with the order you mentioned. From the statement, it is implied that the color changes should be alternate, but the order mentioned in your question is not alternate.

Please see the below code which changes colors on alternate divs through out the scrolling.

$(document).scroll(function() {

  var viewportHeight = $("html").outerHeight();
  var currentY = $(document).scrollTop();
  
  if (Math.floor(currentY / viewportHeight) % 2) {
    lighten();
  } else {
    darken();
  }
});

function darken() {
  $("body").css("background-color", "black");
  $(".panel.content").css("color", "white");
}

function lighten() {
  $("body").css("background-color", "white");
  $(".panel.content").css("color", "black");
}
html,
body,
.panel {
  width: 100%;
  height: 100%;
}

body {
  background-color: black;
  overflow-y: visible;
  overflow-x: hidden;
  transition: background-color 500ms linear;
}

.panel {
  border: 2px solid red;
}

.content {
  color: white;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<body>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
  <div class="panel blank">
  </div>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
  <div class="panel blank">
  </div>
  <div class="panel content">
    <h2> CONTENT </h2>
  </div>
</body>

Upvotes: 0

Related Questions