I'm running the jquery code below in rails:
$(document).ready(function(){
$(".add-new-team-button").on("click", function(){
$(".new-team-form").fadeToggle("fast", function(){
$(".new-team-form").focus();
});
});
});
On the click of a button inside a div on my webpage, it should show or hide a div containing a form( .new-team-form ). However, when the div is visible/showing, I want the browser to put focus on the div because you have to scroll down quite a bit to see it. The fade-toggle is working completely fine. I just cant get it to focus on the form div. My theory on making the focus() action work resulted in the code above and I would be grateful for help on fixing it since it's clearly wrong.
If you want to use focus your div must have a tabindex
attribute on it like:
<div class="new-team-form" tabindex="-1">Add data</div>
alternatively you can use scrollTop
method like:
$(window).scrollTop($('.new-team-form').offset().top);
.focus()
doesn't scroll, .scrollTop(position)
does scroll. JSFiddle with solution . Edit: focus would scroll if called on an input field. scrollTop is a more generic solution though.
Find the first form element and focus on that. Using .find(':input:visible').first().focus()
.
$(document).ready(function(){
$(".add-new-team-button").on("click", function(){
$(".new-team-form").fadeToggle("fast", function(){
$(this).find(':input:visible').first().focus();
});
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.