Marek Sestak
Marek Sestak

Reputation: 1

prevent jump to top jquery tab function on click anchor

I have found this really great Tab Function in the I-net. I have read about the standard problem when using anchors: The Windows jumps to top. Altough there is a e.PreventDefault() and a Live Eventlistener integrated, it is still jumping to top when clicking on the tab. Could you give me an advice?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
    $('ul.tabs').each(function () {
        var $active, $content, $links = $(this).find('a');
        $active = $links.first().addClass('active');
        $content = $($active.attr('href'));

        $links.not(':first').each(function () {
            $($(this).attr('href')).hide();
        });

        // Binde den click event handler
        $(this).on('click', 'a', function (e) {
            // Mache den alten Tab inaktiv
            $active.removeClass('active');
            $content.hide();
            $active = $(this);
            $content = $($(this).attr('href'));
            $active.addClass('active');
            $content.fadeIn(800);
            e.preventDefault();
        });
    });
});
</script>

Upvotes: 0

Views: 1368

Answers (1)

JoDev
JoDev

Reputation: 6873

Search for event.preventDefault, stopPropagation and return false (tested a lot of time)
and also, change the HREF to javascript:void(0) (if you can)

e.preventDefault could not do the trick sometimes. The best way i found is to add return false at the end of the function called onclick.

        // Binde den click event handler
        $(this).on('click', 'a', function (e) {
            e.preventDefault();
            // Mache den alten Tab inaktiv
            $active.removeClass('active');
            $content.hide();
            $active = $(this);
            $content = $($(this).attr('href'));
            $active.addClass('active');
            $content.fadeIn(800);
            e.stopPropagation();
            return false;;
        });

Upvotes: 1

Related Questions