简体   繁体   中英

Scrolling to an element in a bootstrap modal after loading

I have a multiple choice quiz based on a text that the user accesses via a Bootstrap modal. Later when then they review their answers and open the modal, the locations of the answers appear highlighted (targeted as span elements via ID). However, the user has to scroll to find highlighted text that is positioned lower down the modal. Ideally I want the modal to scroll down to these locations automatically after the modal loads.

I'm using this block of code to scroll after the modal loads, but it doesn't scroll..

$(window).on('shown.bs.modal', function() { 
    $('#myModal').animate({
        scrollTop: $('#D6').position().top + $('#myModal').height()
    });
});

Can anyone advise? This is the activity.

Thanks!

The problem here was an attempt to access the postion/dimension of HTML elements (ie #D6 and #myModal ) before they were attached to the DOM.

The solution is to restructure the code, such that those elements are attached to the DOM first, before trying to call their .height() or .position() methods.

The code below is not recommended as a solution, but is provided to give futher insight to the problem:

$(window).on('shown.bs.modal', function() { 

    // 1. If #myModal not attached to DOM, calling $('#myModal').height() returns undefined

    // 2. #D6 not attached to DOM, $('#D6').position().top is not defined

    // 3. Performing this arithmetic, $('#D6').position().top + $('#myModal').height(), will therefore be undefined

    // Assuming #D6 and #myModal will be attached to the DOM, delay access to .height() and .position()
    setTimeout( function() { 

        // We're assuming that #D6 and #myModal are now present in the DOM after this delay. If that is the case, the logic below will correctly calculate an offet value for scrollTop, thus achieving the desired effect
        $('#myModal').animate({ 
            scrollTop: $('#D6').position().top + $('#myModal').height() 
        }); 
    }, 100);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM