Prevent a click on a link from jumping to top of page in Sennajs

540 views Asked by At

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.

3

There are 3 answers

0
stiemannkj1 On

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...

Old Solution (Not Recommended):

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).

5
skay- On

You return before actually calling preventDefault. The following will work:

$(function(){
      $('a').click(function(e) {
         e.preventDefault();
         return false;
      });
    });
3
taesu On

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.