Skip to content

Commit

Permalink
fix: scroll to top on click event (#547)
Browse files Browse the repository at this point in the history
  • Loading branch information
haijian-vaadin committed Feb 12, 2021
1 parent 17b2e3f commit 5c495e9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/triggers/click.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,10 @@ function vaadinRouterGlobalClickHandler(event) {
const {pathname, search, hash} = anchor;
if (fireRouterEvent('go', {pathname, search, hash})) {
event.preventDefault();
// for a click event, the scroll is reset to the top position.
if (event && event.type === 'click') {
window.scrollTo(0, 0);
}
}
}

Expand Down
36 changes: 36 additions & 0 deletions test/triggers/click.spec.html
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,42 @@
expect(clicks[0]).to.have.property('defaultPrevented', true);
});

it('should scroll to top on click event', () => {
const div = document.createElement('div');
div.setAttribute('style', 'width:2000px; height:2000px;');
document.body.append(div);

window.scrollTo(10, 10);
expect(window.scrollX).to.within(9, 11);
expect(window.scrollY).to.within(9, 11);

emulateClick(document.getElementById('in-app'));

expect(window.scrollX).to.within(0, 1);
expect(window.scrollY).to.within(0, 1);
document.body.removeChild(div);
});

it('should not scroll to top on unhandled click event', () => {
preventNavigationDefault = false;

const div = document.createElement('div');
div.setAttribute('style', 'width:2000px; height:2000px;');
document.body.append(div);

window.scrollTo(10, 10);
expect(window.scrollX).to.within(9, 11);
expect(window.scrollY).to.within(9, 11);

emulateClick(document.getElementById('in-app'));

expect(window.scrollX).to.within(9, 11);
expect(window.scrollY).to.within(9, 11);
document.body.removeChild(div);

preventNavigationDefault = true;
});

describe('irrelevant `click` events', () => {
function expectClickIgnored() {
expect(navigateEvents).to.have.lengthOf(0);
Expand Down

0 comments on commit 5c495e9

Please sign in to comment.