Reputation: 371
i tried to add a smoothScroll animation on each button that has a .smoothScroll class.
so i did this:
// SmoothSCroll
var smoothScroll = document.querySelectorAll('.smoothScroll');
[].forEach.call(smoothScroll, function (el) {
el.addEventListener('click', function() {
var offset = $(this.hash).offset().top;
$('html, body').stop().animate({
scrollTop: offset - (window.innerHeight/2) + ($(this.hash).innerHeight()/2)
}, 400 );
return false;
});
});
https://jsfiddle.net/jt2jo3pt/2/
I don't know if you noticed what happened, but there is a little flash when the click triggered ( the scrollbar goes down a little before smoothscrolling )
But when i tried with full Jquery like this:
$('.smoothScroll').click(function(e){
var offset = $(this.hash).offset().top;
$('html, body').stop().animate({
scrollTop: offset - (window.innerHeight/2) + ($(this.hash).innerHeight()/2)
}, 400 );
return false;
});
I don't have this bubbling effect: https://jsfiddle.net/34w72v1v/
Do you have any idea what could cause this issue with querySelectorAll method?
I try to not use jQuery so i need to know what's happening to learn :)
Thanks for your time.
Upvotes: 2
Views: 69
Reputation: 75317
It's because of the return false
. In jQuery, returning false from an event handler prevents the default behaviour taking place. In a (non-inline) JavaScript event handler, it does nothing. For more info, see this excellent answer.
Since your trigger is a <a href="#test" class="smoothScroll">Go to test</a>
, upon clicking it the non-jQuery version is taking you down to the #test
element, but in jQuery it isn't (since the default behaviour is being cancelled)... hence the flash.
If you either don't return false in jQuery, or add e.preventDefault()
in the JavaScript version, you'll notice you can control the flash.
https://jsfiddle.net/34w72v1v/1/
https://jsfiddle.net/jt2jo3pt/3/
Upvotes: 3
Reputation: 93571
You need to preventDefault() in javascript to stop the window moving to the bookmark anchor:
// SmoothSCroll
var smoothScroll = document.querySelectorAll('.smoothScroll');
[].forEach.call(smoothScroll, function (el) {
el.addEventListener('click', function(el) {
el.preventDefault();
var offset = $(this.hash).offset().top;
$('html, body').stop().animate({
scrollTop: offset - (window.innerHeight/2) + ($(this.hash).innerHeight()/2)
}, 400 );
});
});
return false
is just a shortcut used for jQuery events to trigger both e.preventDefault()
and e.stopPropagation()
.
https://jsfiddle.net/TrueBlueAussie/jt2jo3pt/4/
Upvotes: 5