Search code examples
javascriptjquerycsstwitter-bootstraptwitter-bootstrap-tooltip

Bootstrap tooltip not displayed on the first mouse hover action on button


I have a basic back to top Bootstrap button that works perfectly except that its (Bootstrap) tooltip only shows up on the second mouse hovering action, any idea this is not working on the first mouse hovering?

Html side:

<body>
[...]
<a id="back-to-top" href="#" class="btn btn-primary btn-lg back-to-top" role="button" title="Click to return on the top page" data-trigger="hover" data-toggle="tooltip" data-placement="left"><span class="glyphicon glyphicon-chevron-up"></span></a>
[...]
</body>
</html>

JavaScript side:

<script>
    function fadeInBody() {
        $('body').fadeIn(500);
    }

    $(document).ready(function () {
        fadeInBody();

        $(window).scroll(function () {
            if ($(this).scrollTop() > 5) {
                $('#back-to-top').fadeIn();
            } else {
                $('#back-to-top').fadeOut();
            }
        });

        $('#back-to-top').click(function () {
            $('#back-to-top').tooltip('hide');
            $('body,html').animate({
                scrollTop: 0
            }, 800);
            return false;
        });

        $('#back-to-top').tooltip('show');
        $('[data-toggle="tooltip"]').tooltip();
    });
</script>

Solution

  • I managed to reproduce the issue on my side.

    I think the underlying problem is related to your jQuery ready event handler, you actually don't need to call $('#back-to-top').tooltip('show');:

    <script>
        function fadeInBody() {
            $('body').fadeIn(500);
        }
    
        $(document).ready(function () {
            fadeInBody();
    
            $(window).scroll(function () {
                if ($(this).scrollTop() > 5) {
                    $('#back-to-top').fadeIn();
                } else {
                    $('#back-to-top').fadeOut();
                }
            });
    
            $('#back-to-top').click(function () {
                $('#back-to-top').tooltip('hide');
                $('body,html').animate({
                    scrollTop: 0
                }, 800);
                return false;
            });
    
            // Try to comment this out below
            // $('#back-to-top').tooltip('show');
            $('[data-toggle="tooltip"]').tooltip();
        });
    </script>
    

    Let me know if you are still facing the issue.