Search code examples
jqueryprototypejs

Scroll not working after trigger click


I am using $$('.em-details-tabs')[0].scrollTo(); in a function and then trigger a click using $$('DIVELEMENT')[0].click();. The click function is executed successfully but the scroll to a specific element be failed. Here is my code snippet:

$$('a[href="#' + tab_id + '"]')[0].triggerEvent('click');
$$('.em-details-tabs')[0].scrollTo();

Solution

  • The scrollTo() element is only available on the window object, and it also accepts two paramaters; x and y positions.

    To fix this you can use jQuery's scrollTop() method on the window and provide it the y position of the required element. Try this:

    $$('a[href="#' + tab_id + '"]')[0].triggerEvent('click');
    $$(window).scrollTop($$('.em-details-tabs').offset().top);
    

    Working Example

    Alternatively you can amend this logic to make the scroll animate so that the effect is obvious for your users:

    $$('html, body').animate({
        scrollTop: $$('.em-details-tabs').offset().top
    }, 500);
    

    Working Example