Diego Sarmiento
Diego Sarmiento

Reputation: 581

Focus or Autofocus in Input Text doesn't work in Firefox 16.0.2

I want to focus on a input text after page loads/starts. This is my form:

<form method="post" action="tags">
    <input type="hidden" name="id" id="id" value="getId()" />
    <input type="text" name="tag" id="tag" autofocus="autofocus"/>
    <input type="submit" value="Add" name="add" />
</form>

I tried jQuery but it doesn't work on Firefox:

jQuery(document).ready(function(){
  jQuery("#tag").focus();
});

This is a window that opens as Iframe using Fancybox. This is my Fancybox function:

jQuery(".fancybox").fancybox({
    type: "iframe",
    width: 640,
    height: 320,
    afterClose : function() {
        location.reload();
        return;
    },
    afterShow: function() {
        jQuery('.fancybox-iframe').find('#tag').focus();
    }
});

Is there a workaround for this?

Thank you!

Upvotes: 2

Views: 2496

Answers (3)

Diego Sarmiento
Diego Sarmiento

Reputation: 581

I omitted contents() in my answer. In Fancybox v2.x it would be something like:

jQuery(".fancybox").fancybox({
type: "iframe",
width: 640,
height: 320,
afterClose : function() {
    location.reload();
    return;
},
afterShow: function() {
    jQuery('.fancybox-iframe').contents().find('#tag').focus()
}
});

Thank you JFK and Fabrício Matté.

Upvotes: 0

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70169

Try this.

 //change this selector:
$('yourselector').fancybox({
    onComplete: function() {
        $('#fancybox-frame').contents().find('#tag').focus();
    }
});

API reference

As you're loading the content into an iframe, jQuery will not find its contents with the standard $(selector). .contents() and the .find() method will though.

#fancybox-frame is the default ID of the fancybox iframe. The onComplete callback fires when the content is loaded.


After some testing, it seems that the onComplete handler fires too earlier. Using a timeout is an ugly solution, so adapting your loaded page should be a better option:

<form method="post" action="tags">
    <input type="hidden" name="id" id="id" value="getId()" />
    <input type="text" name="tag" id="tag" />
    <input type="submit" value="Add" name="add" />
</form>
<script>
document.getElementById('tag').focus();
</script>

As it is loaded into an iframe, the script will be executed normally and focus the input element as it should.

Upvotes: 1

Jatin
Jatin

Reputation: 1708

you have mentioned id "tag" which doesn't exist

<form method="post" action="tags">
    <input type="hidden" name="id" value="getId()" />
    <input type="text" name="tag" id = "tag" autofocus="autofocus"/>
    <input type="submit" value="Add" name="add" />
</form>

Upvotes: 0

Related Questions