A__
A__

Reputation: 1751

Trouble changing css `top` value to fixed element with js

Trying to move a position:fixed div on scroll by changing the top: css value in javascript. The div won't move though, not sure why.

html:

<div id="red">
  <div id="blue"></div>
</div>

css:

#red {
  position: relative;
  float: left;
  width: 100%;
  height: 1000px;
  background: rgba(255, 0, 0, 0.2);
  border: solid 2px #f0f;
}

#blue {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 50vh;
  background: rgba(0, 0, 255, 0.2);
  border: solid 2px #0ff;
}

js:

window.addEventListener('scroll', function() {
  var yPos = -(Math.floor(document.body.scrollTop / 10));
  //console.log("yPos = " + yPos); //output is correct
  document.getElementById('blue').style.top = yPos + 'px';
  //document.getElementById('blue').setAttribute('top',yPos); //also tried this
});

https://jsfiddle.net/akzx43yL/

Why isn't the top css value changing and how can I get it to do so? No jquery please.

Upvotes: 2

Views: 2289

Answers (3)

user14239
user14239

Reputation: 1

This is what worked for me:

document.getElementById('blue').style.top = yPos + "px";

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42304

Two things:

  • Instead of document.documentElement.scrollTop, you should use window.pageYOffset (scrollTop doesn't play nicely in Chrome).
  • You need to add a unit of measurement after you update top; values other than 0 should have px appened to them.

This can be seen in the following:

window.addEventListener('scroll', function() {
  var yPos = -(Math.floor(window.pageYOffset / 10));
  document.getElementById('blue').style.top = yPos + "px";

  // Optionally log the `top` value
  //console.log(document.getElementById('blue').style.top);
});
#red {
  position: relative;
  float: left;
  width: 100%;
  height: 1000px;
  background: rgba(255, 0, 0, 0.2);
  border: solid 2px #f0f;
}

#blue {
  position: absolute;
  top: -10px;
  left: 0;
  width: 100vw;
  height: 50vh;
  background: rgba(0, 0, 255, 0.2);
  border: solid 2px #0ff;
}
<div id="red">
  <div id="blue"></div>
</div>

Hope this helps! :)

Upvotes: 2

Colin Cline
Colin Cline

Reputation: 1279

If you check your console, you will be see your console.log("yPos = " + yPos) is always 0 you most update your code as follow:

window.addEventListener('scroll', function() {
    var yPos = -(Math.floor(document.documentElement.scrollTop / 10));
    console.log("yPos = " + yPos);
    document.getElementById('blue').style.top = yPos + "px";
});

Tip:
Ways to get srollTop (pure js):

var top  = window.pageYOffset || document.documentElement.scrollTop;

Upvotes: 1

Related Questions