简体   繁体   中英

Add Class on Scroll Issue with Vanilla JS

I am coding a new site for a client and I want to add a class to a div element once the user reaches 100vh. I have given the body an id of "myBody" and the div element that I want to add the class to an id of "quoteForm" and a class of "quote-form" Here is the html of the page...

<body id="myBody">
  <div id="quoteForm" class="quote-form">
    <div id="quoteFormHead"></div>
    <form action="<?php the_permalink(); ?>" method="post">
      <div id="quoteFormBody">
        <div class="formfullwrapper">
          <input type="text" name="message_fname" placeholder="Enter your full name here...">
        </div>
        <div class="formfullwrapper">
          <input type="email" name="message_email" placeholder="Enter your email address here...">
        </div>
        <div class="formfullwrapper">
          <input type="number" name="message_phone" placeholder="Enter your phone number here...">
        </div>
        <div class="formfullwrapper">
          <textarea name="message_msg" placeholder="Details, please! Audience? Word count? Type of document? Tone? Deadlines? Sensitive content?"></textarea>
        </div>
      </div>
      <div id="quoteFormFooter">
        <div class="formfullwrapper">
          <input type="submit" id="submitform" value="Get my free quote">
        </div>
      </div>
    </form>
  </div>
</body>

as you can see its quite a simple form. Below if the javascript logic I have used to add the class name...

document.addEventListener("DOMContentLoaded", function(){
  var scrollElement = document.getElementById('myBody');
  var scrollElementPos = scrollElement.scrollTop;
  var form = document.getElementById('quoteForm');

  scrollElement.addEventListener('scroll', function(){
    scrollElementPos = scrollElement.scrollTop;
    if(scrollElementPos >= 10){
      form.classList.add("form-fixed");
    } else {
      form.classList.remove("form-fixed");
    }
    console.log(scrollElementPos);
  });
});

At present nothing is happening and the class name is not being added to the quote form. Any ideas? Many thanks,

Phillip Dews

Yep its the scroll "On" Window. This is what I came up with and it works a dream...

window.onscroll = function(){
  var top = window.pageYOffset || document.documentElement.scrollTop;
  var form = document.getElementById('quoteForm');
  if (top > 1000) {
    form.classList.add("form-fixed");
  } else {
    form.classList.remove("form-fixed");
  }
}

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