Reputation: 251
I am trying to set focus to an input field in a modal box but I can't get it to work.
Here's the code that I've tried:
// MODAL BOX
$(function() {
$('a[rel*=leanModal]').leanModal({ top : 100, closeButton: ".modal_close" }).find("#first-focus").focus();
});
And
// MODAL BOX
$(function() {
$('a[rel*=leanModal]').leanModal({ top : 100, closeButton: ".modal_close" }).find("input:text:visible:first").focus();
});
Any suggestions on what I can try more?
Upvotes: 1
Views: 579
Reputation: 26
You're using correct method setFocus().
It works fine see this JSFiddle
It means you're probably missing the correct selector.
For the first tag first-focus
is an id, so it can directly be called as $('#first-focus').setFocus();
The link that you've provided for codepen is executing setFocus()
method, which is not defined by jQuery. jQuery method is focus()
. Apart from that this method is called only once. It should be called on click of Open
link.
Your code would now become
// MODAL BOX
$(function() {
$('a[rel*=leanModal]').leanModal({
top: 100,
closeButton: ".modal_close"
}).click(function () {
$('#first-focus').focus();
console.log($("#first-focus").length);
});
});
Here's a working codepen link
It would be best to call the focus()
oncomplete callback of leanModal
however I was unable to find such callback in the documentation or in the source.
Upvotes: 1
Reputation: 4597
Try to do
$("a[rel*=leanModal]").on('click', function(){
$(this).leanModal();
$("#first-focus").focus();
})
Upvotes: 1
Reputation: 67505
Try to access directly to the element by id
:
$("#first-focus").focus();
Hope this helps.
Upvotes: 1