ata
ata

Reputation: 3640

Compare new value with latest in JavaScript

I want to define a var res = 500 then compare it with some other value and if the other value is bigger than LATEST res, then save it on res. The problem is, in every comparison JavaScript is using the initially defined value, mean var res = 500. How can I compare it with the latest value not the initial?

My codes: (Scroll on page. as you can see in red area, res repeatedly jump to 500)

window.onscroll = function() {
      var px = window.scrollY;
      var x = document.getElementsByClassName("sidebar");
      var body = document.body,
        html = document.documentElement;
      var res = 500;
      var pxd = px / 100;
      if (px > 500 && pxd === parseInt(pxd, 10)) {
        if (px > res) {
          res = px;
        }
      }
      if (px > 500 - html.clientHeight) {
        x[0].style.position = "fixed";
        x[0].style.bottom = "10px"
      }

      document.getElementById("text").innerHTML ="res:" + res;
    }
.content {
  height: 10000px;
  width: 100px;
  background-color: blue;
  float: right
}

.sidebar {
  height: 500px;
  width: 100px;
  background-color: red;
  float: left;
  position: static
}
<h1>SCROLL THE PAGE</h1>

<div class="content">

</div>

<aside class="sidebar">
  <p id="text" style="padding-top:400px">res:</p>
</aside>

Upvotes: 0

Views: 41

Answers (2)

Marco Salerno
Marco Salerno

Reputation: 5201

As you wrote it, res is equal to 500 everytime that you scroll the page.

You just need to put

var res = 500;

Out of the window.onscroll function

Upvotes: 1

Deividas
Deividas

Reputation: 6507

This is because you set var res = 500; on every onScroll event. You need to set var res = 500; outside of your window.onscroll function. See example below:

var res = 500;
window.onscroll = function() {
      var px = window.scrollY;
      var x = document.getElementsByClassName("sidebar");
      var body = document.body,
        html = document.documentElement;
      var pxd = px / 100;
      if (px > 500 && pxd === parseInt(pxd, 10)) {
        if (px > res) {
          res = px;
        }
      }
      if (px > 500 - html.clientHeight) {
        x[0].style.position = "fixed";
        x[0].style.bottom = "10px"
      }

      document.getElementById("text").innerHTML ="res:" + res;
    }
.content {
  height: 10000px;
  width: 100px;
  background-color: blue;
  float: right
}

.sidebar {
  height: 500px;
  width: 100px;
  background-color: red;
  float: left;
  position: static
}
<h1>SCROLL THE PAGE</h1>

<div class="content">

</div>

<aside class="sidebar">
  <p id="text" style="padding-top:400px">res:</p>
</aside>

Upvotes: 1

Related Questions