RyNo's
RyNo's

Reputation: 21

Link within a Bootstrap Modal does not work as expected

I have a link inside modal, and I want to take users to a specific location upon clicking. Currently, this works the first time, but any subsequent uses of the same modal when using the "close" button (not the specific link) of the modal, it also sends me to my link (not expected behavior).

Here is a js fiddle that shows the weird behavior of a link in a Bootstrap modal. https://jsfiddle.net/x9kr2wwm/5/

My attempt is a modification of a very similar question/answer (but not a duplicate) found here: CSS Bootstrap close modal and go to link

HTML:

See the <a href="#getstarted" id="gotoLink" data-dismiss="modal">"Get Started"</a> section for more

Javascipt:

jQuery(function($) {
            $("a#gotoLink").click(function(){
                $('#portfolioModal1').on('hidden.bs.modal', function (e) {
                    $('html, body').animate({
                        scrollTop: $("#getstarted").offset().top
                    }, 2000);
                })
           });
    });

Upvotes: 0

Views: 680

Answers (1)

Micros
Micros

Reputation: 165

The default behavior for an <a> element is for the page to be redirected to its href attribute. To prevent the default behavior, use jQuery's .preventDefault() method.

jQuery(function($) {
            $("a#gotoLink").click(function(event){
                event.preventDefault(); 

                $('#portfolioModal1').on('hidden.bs.modal', function (e) {
                    $('html, body').animate({
                        scrollTop: $("#getstarted").offset().top
                    }, 2000);
                })
           });
    });

Upvotes: 1

Related Questions