简体   繁体   中英

How to convert the following jQuery to Javascript for ReactJS?

I have a ReactJS project and I've been advised not to use jQuery for various reasons, so I'm attempting to convert the following jQuery to JavaScript -- it smoothly changes background color while scrolling the page:

$( window ).ready(function() {

    var wHeight = $(window).height();

    $('.slide')
        .height(wHeight)
        .scrollie({
            scrollOffset : -50,
            scrollingInView : function(elem) {

                var bgColor = elem.data('background');

                $('body').css('background-color', bgColor);

            }
        });

    });

CSS:

* { box-sizing: border-box }

body {
    font-family: 'Coming Soon', cursive;
    transition: background 1s ease;
    background: #3498db;
}

p {
    color: #ecf0f1;
    font-size: 2em;
    text-align: center;     
}

a {
    text-decoration: none;
}

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/2542/jquery.scrollie.min_1.js"></script>

<div class="main-wrapper">

    <div class="slide slide-one" data-background="#3498db">
        <p>Title</p>
        <center>Go To <a href="#green" style="color:green">Green</a>.</center>  
    </div>

    <div class="slide slide-two" data-background="#27ae60">
        <a name="green">
            <p>Green area</p>
            <center>Go To <a href="#red" style="color:red">Red</a>.</center>
        </a>
    </div>

    <div class="slide slide-three" data-background="#e74c3c">
        <a name="red">
            <p>Red area</p>
            <center>Page over. Hope that was helpful :)</center>
        </a>
    </div>

But how can I do the conversion to JavaScript to fit the ReactJS project?

Thank you in advance and will be sure to accept/upvote answer

Changing from JQuery to JavaScript is always possible. Because JQuery builds on JavaScript. Most of the time ( like in your case ) it's not even that much work.

I've not changed your CSS or HTML. So this is just some new JavaScript. However you should put this script at the end of your website.

(function() { // create an own scope and run when everything is loaded

  // collect all the slides in this array and apply the correct height
  var slides = document.getElementsByClassName('slide')
  for (slide of slides) slide.style.height = window.innerHeight + 'px'

  // use the native scroll event
  document.addEventListener("scroll", function() {
    // how much have we scrolled already
    var currentOffset = document.documentElement.scrollTop || document.body.scrollTop

    // now check for all slides if they are in view (only one will be)
    for (slide of slides) {
       // 200 is how much before the top the color should change
       var top = slide.getBoundingClientRect().top + currentOffset - 200
       var bottom = top + slide.offsetHeight

      // check if the current slide is in view
      if (currentOffset >= top && currentOffset <= bottom) {
        // set the new color, the smooth transition comes from the CSS tag
        // CSS: transition: background 1s ease;
        document.body.style.background = slide.dataset.background
        break
      }
    }

  })

}())

Additionally you might want to listen on resize event, because as of now when you resize the window will look a bit off ( this replaces the 5 line of the code above)

  function setSize() {
    for (slide of slides) slide.style.height = window.innerHeight + 'px'
  }
  window.addEventListener("resize", setSize)
  setSize()

Solution

 (function() { var slides = document.getElementsByClassName('slide') function setSize() { for (slide of slides) slide.style.height = window.innerHeight + 'px' } window.addEventListener("resize", setSize) setSize() document.addEventListener("scroll", function() { var currentOffset = document.documentElement.scrollTop || document.body.scrollTop for (slide of slides) { // 100 is how much before the top the color should change var top = slide.getBoundingClientRect().top + currentOffset - 100 var bottom = top + slide.offsetHeight if (currentOffset >= top && currentOffset <= bottom) { document.body.style.background = slide.dataset.background break } } }) }())
 body { font-family: 'Coming Soon', cursive; transition: background 1s ease; background: #3498db; } p { color: #ecf0f1; font-size: 2em; text-align: center; } a { text-decoration: none; }
 <div class="main-wrapper"> <div class="slide slide-one" data-background="#3498db"> <p>Title</p> <center>Go To <a href="#green" style="color:green">Green</a>.</center> </div> <div class="slide slide-two" data-background="#27ae60"> <a name="green"> <p>Green area</p> <center>Go To <a href="#red" style="color:red">Red</a>.</center> </a> </div> <div class="slide slide-three" data-background="#e74c3c"> <a name="red"> <p>Red area</p> <center>Page over. Hope that was helpful :)</center> </a> </div>

The plugin you are referring to links an example from their README that includes a link to a newer version that makes use of this other plugin that does not use jQuery and in fact does what you want it to do, I think. It is called in-view and it looks very good to me (both the functionality and the code).

Its usage is very similar to what you are doing currently. From the newer example linked above:

var $target = $('.wrapper');
inView('.section').on('enter', function(el){
  var color = $(el).attr('data-background-color');
  $target.css('background-color', color );
});

I do realize that I am in a way not answering the question, because this is not a jQuery-to-vanilla-JS guide, but I do think that it helps to know that somebody already did it for you.

Should give you some idea.

var wHeight = window.innerHeight;

To select elements in javascript: on browser open inspect element, console tab and type:

document.get

and it gives you hint what to get

To get style of element:

 var elem1 = document.getElementById("elemId");
 var style = window.getComputedStyle(elem1, null);

To set Property:

 document.body.style.setProperty(height`, wHeight  +"px");

Below is some modifications that you can make, As people commented I am not trying to teach you how to's but want to give you some start:

 // $( window ).ready(function() { //remove this

var wHeight = $(window).height(); // USe this instead: var wHeight = window.innerHeight;

$('.slide') //instead of selecting with jquery "$('.slide')"  select with:  Javascript var x = document.getElementsByClassName("example") ;
  .height(wHeight) // Here you are chaining methods, read this article https://schier.co/blog/2013/11/14/method-chaining-in-javascript.html
  .scrollie({
    scrollOffset : -50,
    scrollingInView : function(elem) {

      var bgColor = elem.data('background'); //var bgColor = window.getComputedStyle(elem, null);

      $('body').css('background-color', bgColor); //document.body.style.background = bgColor;

    }
  });

 // }); //remove this

For .... in

var t = document.getElementsByClassName('slide')
console.log(typeof t) //object

for (var prop in t) {
 console.log('t.' + prop, '=', t[prop]);
 // output is index.html:33 t.0 = <div class=​"slide slide-one" data-      background=​"#3498db">​…​</div>​
 // output is index.html:33 t.1 = <div class=​"slide slide-two" data- background=​"#27ae60">​…​</div>​
 // output is index.html:33 t.2 = <div class=​"slide slide-three" data-background=​"#e74c3c">​…​</div>​<a name=​"red">​…​</a>​</div>​
// output is index.html:33 t.length = 3
// output is index.html:33 t.item = function item() { [native code] }
// output is index.html:33 t.namedItem = function namedItem() { [native code] }

}

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