Question: I have such problem - I need to autofocus some element inside twitter bootstrap modal (after it shows). The tricky part is here - content of this modal is loaded using 'data-remote' (jQuery.load method) from separate HTML file, so

```
$(document).on('shown', ".modal", function() {
    $('[autofocus]', this).focus();
});

```

works only if modal was loaded before.   

The question is - how to make autofocus work at the first time modal loads?

Answer: 
Above answers are somewhat outdated for latest Bootstrap versions.
------------------------------------------------------------------

Below is excerpted from: <http://getbootstrap.com/javascript/#modals>

> 
> Due to how HTML5 defines its semantics, the `autofocus` HTML attribute
>  has no effect in Bootstrap modals. To achieve the same effect, use
>  some custom JavaScript:
> 
> 
> 
> ```
> $('#myModal').on('shown.bs.modal', function () {
>   $('#myInput').focus()
> })
> 
> ```
> 
>
The accepted answers handle focusing on the autofocus button in the modal, but don't restore focus to the main page afterwards. This may be undesirable if you're showing the modal from a form that the user expects to submit afterwards by pressing enter.

So here's the complete code that handles both showing and hiding the modal:

```js
// All modals will take enter to mean clicking the button with the autofocus property
$(document).ready(function () {
    $('.modal').on('shown.bs.modal', function() {
        $(this).find('[autofocus]').focus();
    });
    $('.modal').on('show.bs.modal', function(e) {
        var activeElement = document.activeElement;
        $(this).on('hidden.bs.modal', function () {
            activeElement.focus();
            $(this).off('hidden.bs.modal');    
        });
    });
});

```

> 
> Note: This code clears out all event listeners on the modal's `hidden.bs.modal` event. If you have other listeners for that event, then you'll need to turn the hidden function into a named function that you can reference and remove by reference from the event listeners.
> 
> 
>