AnimaSola
AnimaSola

Reputation: 7856

Scroll to Element through href conflicts with Bootstrap modals

I have this code that scrolls to specific elements when their ID is put in hrefs (demo here):

$('a[href*=#]:not([href=#])').click(function () {
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
                || location.hostname == this.hostname) {

                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    $('html,body').animate({
                        scrollTop: target.offset().top - 125
                    }, 1000);
                    return false;
                }
            }
        });

Problem is, I think it conflicts with the Bootstrap JS components, especially the modal. Now, opening my modal doesn't seem to work like it did before:

LINK:

<a href="#myModal" role="button" class="btn btn-primary btn-large" data-toggle="modal">Sign-up for Beta!</a>

JS:

 $('#myModal').modal({
                keyboard: true,
                show: false,
                backdrop: 'static'
            });

ELEMENT:

<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
</div>

Can anyone help me resolve this conflict? Any piece of advice would be highly appreciated. Thanks!

Upvotes: 1

Views: 873

Answers (1)

AnimaSola
AnimaSola

Reputation: 7856

I actually found the answer with some trial and error.

I noticed that the first line $('a[href*=#]:not([href=#])') actually looks for all anchor elements which is kinda bad. With some little research on HTML 5 data attributes, I got it to work:

Replace: $('a[href*=#]:not([href=#])')

With: $('[data-toggle="elementscroll"]')

Next thing to do is place the HTML 5 attribute on each of your anchor links, like below:

<a href="#Seamless" data-toggle="elementscroll">Seamless</a>

Hope this helps anybody out there!

Upvotes: 1

Related Questions