Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery scrollTop and focus on element

I have the following scrollTop function:

<a onclick="jQuery('html,body').animate({scrollTop:0},'slow');return false;" class="well well-sm" href="#">
                    <i class="uxf-icon uxf-up-open-large"></i><span class="sr-only">${message:backToTop}</span></a>

However, when you use your keyboard to navigate the focus does not go to the top. It remains in the footer. Is there a way to bring the focus to the following div:

<div id="top" tabindex="-1"></div>
like image 546
j00m Avatar asked Jul 16 '26 12:07

j00m


2 Answers

The visual focus is different from the keyboard focus, you can use the focus() function to define the keyboard focus

 <a onclick="jQuery("#top").focus();return false;" class="well well-sm" href="#">...</a>

This can be used conjointly with your animate function.

like image 137
Adam Avatar answered Jul 18 '26 01:07

Adam


Animated scrolling to the top of the element, then setting a focus:

<script>
    function scroll() {
        $('html, body').animate({
            scrollTop: $('#top').offset().top
        }, 'slow', function() { 
            $('#top').focus(); 
        });
    }
</script>
<a onclick="scroll(); return false;" class="well well-sm" href="#">...</a>
like image 33
Adam Libuša Avatar answered Jul 18 '26 01:07

Adam Libuša



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!