Soheil
Soheil

Reputation: 31

Javascript code for focusing on a certain div after loading the page

I'm trying to make a page horizontally and my problem is, and it starts from the end(DIVs are defined in right-to-left order, and it shows the one which is on the left) I need a function to tell the browser to focus on the right div onload,so the user won't get confused. thank you. s.rb

Upvotes: 1

Views: 1783

Answers (3)

ruswick
ruswick

Reputation: 154

Vanilla JS

There is a focus function that can be called on an html element:

document.querySelector('#myElement').focus();

You can read more about it on the Mozilla Documentation site.

jQuery

If you're using jQuery, you can also use the built-in jQuery focus() method:

$('#myElement').focus();

Upvotes: 0

brk
brk

Reputation: 50291

You can do something like this

Set tabIndex to the element which you want to focus.

HTML

<div id = "iWillBFocused">
 I will be focused on referesh 
</div>

JS

document.getElementById('iWillBFocused').focus()

JSFIDDLE

Upvotes: 2

Niles Tanner
Niles Tanner

Reputation: 4021

By focus I assume you mean you want to scroll to the correct div on load.

if the div was defined like:

<div id="main"></div>

you can scroll to it in javascript with:

window.location.hash = '#main';

I hope this helps

Upvotes: 4

Related Questions