JGallardo
JGallardo

Reputation: 11373

How to make one element disappear after you made another one appear using javascript. triggered by scrolling?

I have text inside an element that will appear in the header when you scroll down.

But then I also want to make the first section of the page disappear at the same time. So i set the javascript at the same scroll point. This is a small feature, I don't want to rely on any library. So just plain javascript solution suggestions please.

HTML

<header class="header-home">
  <div>
    Company
  </div>
  <span class="header-copy">
    is so awesome
  </span>

  <button></button>  
</header>

<!-- test content -->
<section class="landing-bg">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
  <img src="http://placehold.it/350x150">
</section> 

Javascript

I started with the top block of code and all worked fine to make the text in the header-copy to appear when you scroll 300px.

var span = document.querySelectorAll('.header-home .header-copy')[0];

span.style.display = "none";

document.addEventListener("scroll", function() {
  if (document.body.scrollTop > 300) {
    span.style.display = "inline-block";
  }
  else {
    span.style.display = "none";
  }
});

But then I wanted to make the first section in my page go away.

/* makes the top content go away */

var content = document.getElementsByClassName("landing-bg")[0];

content.style.display = "block";

document.addEventListener("scroll", function() {
  if (document.body.scrollTop > 300) {
    content.style.display = "none";
  }
  else {
    content.style.display = "block";
  }
});

A full demo is available on CodePen

Upvotes: 0

Views: 66

Answers (1)

JGallardo
JGallardo

Reputation: 11373

I ended up nesting the code and verifying class names. Answering this rather than deleting just in case someone can use this code as an example.

Javascript

/* Allows you to select a class within a class */
var span = document.querySelectorAll('.header-home .header-copy')[0];
span.style.display = "none";

/* you can select an element with a specific class*/
var content = document.getElementsByClassName("landing-bg")[0];
content.style.display = "block";

document.addEventListener("scroll", function() {
  /* edit to the scroll point that you need */
  if (document.body.scrollTop > 300) {
    span.style.display = "inline-block";
    content.style.display = "none";
  }
  else {
    content.style.display = "block";
    span.style.display = "none";
  }
});

Upvotes: 1

Related Questions