So I started learning ES6 and modular JS(with Webpack), and now I would like to refactor this old script for the Return to top arrow, and turn it into a ES6 style script with constructor and all. This is what I got for now, but can't figure out how to write conditional statement inside a ScrollTop class..any ideas?
I am trying to write and access the conditional logic somehow, but don't know how to implement $(window).scroll etc. into the class. Do I need a new function that takes care of this..? I want it to work the same, but write it more cleanly.
Old script:
$(window).scroll(function() {
if ($(this).scrollTop() >= 200) {
$('#return-to-top').fadeIn(200);
} else {
$('#return-to-top').fadeOut(200);
}
});
$('#return-to-top').click(function() {
$('body,html').animate({
scrollTop : 0
}, 300);
});
<a href="#" id="return-to-top"><i class="fa fa-chevron-up"></i></a>
New script:
import $ from 'jquery';
class ScrollTop {
constructor() {
this.scrollUp = $("#return-to-top");
this.topDistance = $("#return-to-top").offset().top;
this.events();
}
events() {
this.scrollUp.click(this.returnToTop.bind(this));
}
returnToTop() {
$('body,html').animate({
topDistance: 0
}, 3000);
}
}
export default ScrollTop;