How to scroll to an element within a modal using jquery?

If you want to use this with a Bootstrap Modal be sure to use

$("#modalcontent").animate(...);

because it's the modal content that has the scroll bars.

Also useful might be the use of a placeholder after the content you want to show. Consider this: You have a modal and at the very end you have a button, e.g. to submit a form inside your modal. After the submission is completed you might want to show a confirmation or an error within the modal. Because the message you want to show shouldn't be placed within your form you might want to place it under the button. BUT if your modal alread has scrollbars it doesn't scroll automatically when showing your message, e.g. with a Bootstrap alert. That's because the solutions above reference the top corner of your message. To resolve this you can add an offset to your position like

$("#modalcontent").animate({scrollTop: $('#messagebox').offset().top + offset}, 200);

or you can add a placeholder right below your alert.

$("#modalcontent").animate({scrollTop: $('#placeholder').offset().top}, 200);

And sometimes it's apropriate to combine these two options, e.g. when you have other alerts inside your form which still are visible when you show the submission message.


It looks like you are calling the animate method on html and body.

$('html, body').animate(...);

If you want to scroll the modals window you have to call the animate method on that element instead.

$('#modal').animate(...);

Where #modal is the element containing the elements you've created.

edit:

I see that you tried to call animate on the modal. Here is a fiddle that scrolls elements in a modal when you click the button.

also in the code you have a closing bracket after #Element which is causing the script to error: ...scrollTop: $('#Element'])...