March 30, 2011
add an anchor and onClick to a link
Question by Denoteone
I have an image with a link that when clicked I would like the user to be brought to an anchor on the same page and then the cursor to be focused on the input directly below.
<a onclick="document.newsletter.email.focus();" href="#newssection"><img src="images/newsletter_slide.jpg" /></a>
When it is just the onClick it works but does not scroll the page down and when I use the anchor it goes to that section but does not focus.
I switched around the onClick and the href and it didnt help
Answer by Kyle
Try this.
<a onclick="document.newsletter.email.focus();return false;" href="#">click me</a>
<form name="newsletter" id="newssection">
<input id="email" name="email"/>
</form>
Answer by Starx
I think a simple
document.getElementById('yourEmailField').focus();
should do the trick.
It will automatically focus to the element, and if needed scroll too.