How do I close a Modal window and automatically navigate to Anchor using the same link?

10,655

Solution 1

Have you tried or thought about a jquery onclick function on the close button?

Maybe you can force the modal to close manualy with (see docs)

$('#myModal').modal('hide');

and navigate to the anchor using (see answer)

$(document.body).scrollTop($('#anchorId').offset().top);

and the result will be:

HTML:

<a class="btn btn-info" href="#" id="contact_btn">Contact Us</a>

jquery:

$('#contact_btn').click(function(){
    $('#myModal').modal('hide');
    $(document.body).scrollTop($('#anchorId').offset().top);
});

Solution 2

I have experienced the same issue, but the answer provided by Lan did not work for me.

Finally, I work it out by using onClick to close modal class .modal instead of using the id of the particular modal #myModal I wanted to close. This works because you can only have one modal open at a time in your web:

<a href="#section-contact" onClick="$('.modal').modal('hide');">Contact us</a>

Solution 3

Js

// .my-anchor = the class of the trigger
$('.my-anchor').on('click', function(e) {
    e.preventDefault();

    // it will search throughout .my-anchor ancestors to find the closest .modal
    $(this).closest('.modal').modal('hide');

    var hash = this.hash;

    $('html, body').animate({ scrollTop: $(hash).offset().top }, 300);
});

HTML

// clicking this link will close the modal and scroll to wherever #products is located on the page
<a href="#products" className="my-anchor">Click Here</a>

In this example, hash will be #products, but it will update to any other anchor you might have

Share:
10,655
Metzed
Author by

Metzed

Updated on June 05, 2022

Comments

  • Metzed
    Metzed about 2 years

    I'm using Bootstrap 3.0 and I have an open Modal window with two 'buttons' at the bottom, one says 'Contact Us' and the other says 'Close'.

    When someone clicks the 'Contact Us' button I want the Modal window to close and the user to be automatically taken to a specific anchor on the same page.

    The following doesn't work. It does scroll the page to the desired anchor, but the user can't see this because it doesn't close the modal window...

    <a class="btn btn-info" data-dismiss="modal" href="#section-contact">Contact Us</a>
    
  • Metzed
    Metzed over 10 years
    Thanks, I have multiple modal windows with the same contact button within them, so I came up with the following code using a class name instead of ID. It seems to work. I also had to add $('body, html') because $(document.body) didn't seem to work in IE8. Does it look ok? $('.my_contact_button').click(function(){ $().modal('hide'); $('body, html').scrollTop($('#section-contact').offset().top); });
  • Lan
    Lan over 10 years
    If it works for your case, use classname, name or id! whatever you need to do the trick! :D