miyasudokoro
miyasudokoro

Reputation: 1745

Trigger click on div so it will scroll on pagedown and pageup

When I physically use the mouse to click on my div, then pageUp and pageDown scroll the div. However, when I programmatically trigger a click on the div, then pageUp and pageDown fail to scroll the div. How can I get pageUp and pageDown to scroll the div without the user having to physically click in the div?

Details:

What I am trying to do is to let the user pageDown to the bottom of the div, then one more pageDown loads the next set of content into the div and auto-scrolls to the top; and vice versa for pageUp. It works great as long as the user has clicked inside the div. I am trying to make it so they don't have to actually click in the div to be able to scroll via pageDown or pageUp.

I am certain that the programmatic click is happening because the click event listeners get triggered. My pageUp listener also works to load the previous set of content (because the scroll bar starts out at the top).

I am developing within Node-Webkit (Chrome) and angular.js, but cross-browser support is also necessary.

Things I have tried:

$('#div').click();
$('#div')[0].click();
$('#div').trigger('click');
$('#div').focus();
$('.focusableThingInsideDiv').focus();
$('#div').scroll();  //just trying random things at this point

I have also tried stopping the default browser behavior and implementing the scroll myself (via setting scrollTop). This technically works. However, I would prefer not to override the default behavior if possible.

Upvotes: 3

Views: 1802

Answers (1)

m4ktub
m4ktub

Reputation: 3121

The page up and page down work, after you click on the div, because it gains focus. So, although it does not show as a focused element after clicking, you still want the $('#div').focus() line.

The tricky part is that to be able to focus on a div programatically you need to give it a tabindex. Something like <div tabindex="0">...</div> will make the focus suddenly work in Chrome.

Other browsers (IE and Firefox) do not seem to required this. The focus() will work from the start but adding tabindex=0 will not hurt.

Upvotes: 3

Related Questions