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.

http://jsfiddle.net/HgSjH/3/

<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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!