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');
}
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With