hnnnng
hnnnng

Reputation: 495

Closing Bootstrap modal with a click to navigation to an element

I have a modal with some content and a button. The button should scroll the user towards the bottom of the page to an element. I saw similar questions but none of those answers helped me my case in my CMS. The only way it worked for me was to set a timeout and delay the modal close but now page scroll back to top as soon as the modal closes. This is what's happening now 1. The modal opens and user clicks on the button in the modal 2. The page scrolls to the bottom and the modal closes 3. and then the page scrolls back to top on its own upon modal closure.

It's like the Url with # is not persistent and it's only valid while the modal is open. Once the modal is closed everything resets and the page scrolls back to default (top).

This is my code:

$('#request-btn').click(function() {
    var $modalDialog = $("#modalPopup");
    setTimeout(function() {
      $modalDialog.modal('hide');
    }, 1000);
});

and this is my modal markup:

<div aria-hidden="true" aria-labelledby="exampleModalLabel" class="modal fade" id="modalPopup" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <h4>
          READY FOR THE NEXT STEP?
        </h4>
      </div>

      <div class="modal-footer">
        <a class="btn red-btn" href="#next-step" id="request-btn">REQUEST MORE INFO</a>
      </div>
    </div>
  </div>
</div>

Upvotes: 1

Views: 565

Answers (1)

user1575941
user1575941

Reputation:

Not really a BS5 question .. more generic JS. I also see that you've used jQuery in your question so I'll use that to answer. There are many ways to do these ... question #6677035 does this with animation:

<div aria-hidden="true" aria-labelledby="exampleModalLabel" class="modal fade" id="modalPopup" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <h4>
          READY FOR THE NEXT STEP?
        </h4>
      </div>

      <div class="modal-footer">
        <a class="btn red-btn" href="#next-step" id="request-btn">REQUEST MORE INFO</a>
      </div>
    </div>
  </div>
</div>

<div class="m-4 container">
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalPopup">
        Launch demo modal
    </button>
    
    <div style="height:2000px"></div>
    
    <p id="whereweshouldbe">THE OTHER CONTEXT HERE</p>
</div>
  $('#request-btn').click(function() {
    var $modalDialog = $("#modalPopup");
    setTimeout(function() {
      $modalDialog.modal('hide');
      $([document.documentElement, document.body]).animate({
        scrollTop: $("#whereweshouldbe").offset().top
      }, 1000);
    }, 1000);
  });

Upvotes: 1

Related Questions