Popup modal and jump to anchor inside

Popup modal and jump to anchor inside

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
  1. <a href="#contributors" class="element-item item1">item1</a>
  2. <a href="#contributors" class="element-item item2">item2</a>
  3.         
  4. <!-- The Modal -->
  5. <div id="contributors" class="modal">
  6. <header><span class="close">×</span></header>
  7. line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line
  8. <div class="item" id="item1"><h4>Item 1</h4></div>
  9. <br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line
  10. <div class="item" id="item2"><h4>Item 2</h4></div>
  11. <br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line
  12. </div>

JS
  1. //popup nested modals
  2. $(function () {
  3. const openModals = [];
  4. $('.element-item').click(e => {
  5. e.preventDefault();
  6. $(e.currentTarget).closest('.modal').add('body').addClass('open');
  7. openModals.push($($(e.currentTarget).attr('href')).show());
  8. });
  9. $(window).add('.close').click(e => {
  10. e.stopPropagation();
  11. if ($(e.target).is('.modal, .close')) {
  12.   const closing = openModals.pop().addClass('modal-content-active');
  13.   setTimeout(() => {closing.hide().removeClass('modal-content-active')}, 0);
  14.   if (openModals.length > 0) {
  15.     openModals[openModals.length - 1].removeClass('open');
  16.   } else $('body').removeClass('open');
  17. }
  18. });
  19. });

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

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