Skip to main content

Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #297253
    j7f4f2a4fds2
    Participant

    Hi all,

    I am trying to create a link that when clicked, a modal pops up, and also jumps to an anchor in it.

    At the moment you will see i have some code for the pop up (which is configured for a set of nested modals) hence it is not your standard setup.

    When you click on the links twice, they work. How can I get it to work as is, with one click only.

    Thanks

    HTML
    item1
    item2

    JS
    //popup nested modals
    $(function () {
    const openModals = [];
    $(‘.element-item’).click(e => {
    e.preventDefault();
    $(e.currentTarget).closest(‘.modal’).add(‘body’).addClass(‘open’);
    openModals.push($($(e.currentTarget).attr(‘href’)).show());
    });
    $(window).add(‘.close’).click(e => {
    e.stopPropagation();
    if ($(e.target).is(‘.modal, .close’)) {
    const closing = openModals.pop().addClass(‘modal-content-active’);
    setTimeout(() => {closing.hide().removeClass(‘modal-content-active’)}, 0);
    if (openModals.length > 0) {
    openModals[openModals.length – 1].removeClass(‘open’);
    } else $(‘body’).removeClass(‘open’);
    }
    });
    });

    //jump to anchor in modal
    $(‘.item1’).on(‘click’,function(){ $(‘#contributors’).animate( { scrollTop: $(‘#item1’).offset().top -40 }, 500); });
    $(‘.item2’).on(‘click’,function(){ $(‘#contributors’).animate( { scrollTop: $(‘#item2’).offset().top -40 }, 500); });

    CSS
    .modal{ width: 300px; height: 200px; overflow: auto; display: none; }

    Here is a fiddle: https://jsfiddle.net/postcolonialboy/x28bw14d/

    #297254
    j7f4f2a4fds2
    Participant

    over at stackexchange @marzelin suggested the following which works fine:


    The problem is that the layout updates only after both click handlers are done. A quick fix is to wrap a handler with requestAnimationFrame:

    $(‘.item1’).on(‘click’,function(){ requestAnimationFrame(() =>
    $(‘#contributors’).animate( { scrollTop: $(‘#item1’).offset().top -40 }, 500)
    )});

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.