I'm a newbie to javascript, so please forgive if I ask things that are painfully obvious.
I am using Sennajs for my personal project. I have a issue like in gallery example . When click a link, it makes the page jump to the top. I used to use this code from jquery to fix it. However it also prevents senna from working.
$('a').click(function(e) {
// do something
return false;
e.preventDefault();
});
Any help would be very appreciated.
It turns out that you can use app.setUpdateScrollPosition(false)
to avoid jumping to the top of the page after every SennaJS navigation:
var app = new senna.App();
app.setUpdateScrollPosition(false);
// ...your code here...
Note: this solution is unnecessarily overcomplicated since I wrote it before I knew about app.setUpdateScrollPosition(false)
.
Instead of preventing SennaJS from executing, you could save the current scroll position before navigating and scroll to the correct position after navigating:
var app = new senna.App();
// ...your code here...
function getScrollTop() {
// Taken from Engineer's answer:
// https://stackoverflow.com/questions/11193453/find-the-vertical-position-of-scrollbar-without-jquery#11193613
return (window.pageYOffset !== undefined) ? window.pageYOffset :
(document.documentElement || document.body.parentNode || document.body).scrollTop;
}
var scrollTop = getScrollTop();
app.on('beforeNavigate', function(event) {
scrollTop = getScrollTop();
});
app.on('endNavigate', function(event) {
window.scrollTo(0, scrollTop);
});
For more information about scroll positions and JavaScript, see Engineer 's answer here and MDN's window.scrollTo()
documentation .
For more information about SennaJS Lifecycle Events, see the SennaJS documentation
Note: this may be a bug in SennaJS, so I've created a bug report (#184) .
You return
before actually calling preventDefault
. The following will work:
$(function(){
$('a').click(function(e) {
e.preventDefault();
return false;
});
});
The reason why your code doesn't work is because you return
before doing anything.
$('a').click(function(e) {
e.preventDefault();
// do something
return false;
});
so, do something after you prevent the normal behaviour first.
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.