简体   繁体   中英

Strange behavior of Tumblr when adding JS

first of all I'm kinda new to JavaScript. However I wrote a tiny script to check if the DOM is ready and then fix the header of my tumblr blog when the page is scrolled.

My code looks like this:

document.addEventListener("DOMContentLoaded", function() {
console.log("DOM ready!");

function fixHeader() {
  var header = document.querySelector("#js--site-header");
  var offset = 100;
  // only used to see the current offset when debugging
  console.log(window.scrollY);

  window.scrollY >= offset 
      ? header.classList.add("js--header-fixed") 
      : header.classList.remove("js--header-fixed");
 };

document.addEventListener("scroll", fixHeader);
});

I simulated the exact same code on CodePen to test if it's a bug inside my code or a problem with Tumblr. By now it seems like Tumblr is the problem. Whenever I scroll the page over 100px it reloads instead of fixing the header to the top. On CodePen everything works as expected and the header get's fixed.

You can see my blog with the not-working code from above here (NSFW)

Every help or hint would be appreciated, I've no idea what I'm doing wrong.

What you are experiencing is not a reload (you can use tools like Firebug to see whether your browser creates any HTTP requests). The problem in your tumblr blog is that the "header" you are trying to fix also contains the whole content. Thus, as soon as 100px offset is reached, the whole content is fixed and no scrollable content is left. The scroll offset falls back to 0, your event handler is triggered a second time and the event handler un-fixes the "header" again.

Move your </header> in front of <main class="content"> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM