Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Focus after animate

I want to set focus on a textbox of id let's say txtName after scrolling to top of page using div.focus and animate().

Is there a functionality that specifies to focus after animate like document.ready would perform after document.ready?

The code I used to scroll is given below.

$(".gototop").click(function(){ 
    var focusElement = $("#contents"); 
    $(focusElement).focus(); 
    ScrollToTop(focusElement); 
}); 

function ScrollToTop(el) { 
    $('html, body').animate({ scrollTop: $(el).offset().top - 50 }, 'slow');           
} 
like image 556
Archana David Avatar asked Sep 15 '25 05:09

Archana David


2 Answers

You can set focus to an element in animate's callback, that way it will receive focus when the animation is completed:

function ScrollToTop(el) { 
    $('html, body').animate({ 
        scrollTop: $(el).offset().top - 50 }, 
    'slow', function() {
        $("#txtName").focus();
    });           
} 

and if el is the element you wish to focus, you can use the passed variable instead of #txtName

like image 132
adeneo Avatar answered Sep 16 '25 18:09

adeneo


The animate function accepts a callback that will be executed once the animation is complete. You can do something like this:

$(".gototop").click(function(){ 
    var focusElement = $("#contents");
    ScrollToTop(focusElement, function() { focusElement.focus(); }); 
}); 

function ScrollToTop(el, callback) { 
    $('html, body').animate({ scrollTop: $(el).offset().top - 50 }, 'slow', callback);
} 
like image 43
Kristof Claes Avatar answered Sep 16 '25 20:09

Kristof Claes