NinjaBoy
NinjaBoy

Reputation: 3755

How to focus on a particular portion of a web page using JavaScript?

Can somebody tell me how to focus on particular part of a web page by using JavaScript events? Let's say I clicked a button and it will scroll down or scroll up to a particular portion a page. Here is my incomplete code:

<html>
<head>
<script type="text/javascript">
 function focusOnForm() {
  document.getElementById('form').style.display = '';
 }
</script>
</head>
<body onload="document.getElementById('form').style.display = 'none';">
<div style="height: 900px; width: width: 500px; background-color: #000;">
</div>
<br />
<input type="button" value="Add" style="float: right;" onclick="focusOnForm();" />
<br />
<div id="form">
 First Name: <input type="text" /> <br />
 Last Name: <input type="text" /> <br />
 Address: <input type="text" /> <br />
 Contact Number: <input type="text" /> <br />
 Email: <input type="text" /> <br />
</div>
</body>
</html>

I really need help.

Upvotes: 4

Views: 4709

Answers (2)

ThinkingStiff
ThinkingStiff

Reputation: 65381

You can scroll to a pixel location with:

document.body.scrollTop = 2000;

http://jsfiddle.net/ThinkingStiff/A7JMZ/

Upvotes: 2

Rob W
Rob W

Reputation: 349232

Use the .scrollIntoView() method:

 function focusOnForm() {
    var form = document.getElementById('form');
    form.style.display = '';
    form.scrollIntoView();
 }

Fiddle: http://jsfiddle.net/g8Mqr/

Upvotes: 3

Related Questions