Synchronizing the Scrollbar in JavaScript
If you have two text areas on a Web page and need to synchronize the scrollbars, you can do this using the jQuery JavaScript library and the "scrollTop" function. The "scrollTop" function returns the number of pixels that are hidden from view in a scrolling text area. By getting the "scrollTop" value for one text area and setting it as the "scroll" value for both text areas, you can connect the scrollbar states. This allows you to scroll up or down in one text area and the second text area will scroll up or down by the same number of pixels.
Instructions
-
-
1
Open your Web page document in an HTML or text editor. To open your document in a native Windows text editor, right-click the file, then click "Open With." Click to select "Notepad" or "WordPad," then click "OK."
-
2
Click to place your cursor between the "<head>" and "<head>" tags near the top of the document. Press "Enter" to create a blank line.
-
-
3
Type "<script src='http://code.jquery.com/jquery-latest.js' type='text/javascript'></script>" and press "Enter" to link your Web page document to the jQuery JavaScript library.
-
4
Type "<script type='text/javascript'>" to open a scripting tag. Press "Enter."
-
5
Type "$(function() {" and press "Enter." This line of code opens the main script function statement.
-
6
Type "$('textarea[id$=textarea1]').scroll(function() {" and press "Enter." This line of code returns the "id" and "scroll" value for the "textarea1" text area element.
-
7
Type "$('textarea[id$=textarea2]')" and press "Enter." This line of code returns the "id" value for the second text area.
-
8
Type ".scrollTop($('textarea[id$=textarea1]').scrollTop());" and press "Enter." This line of code invokes the "scrollTop" function to synchronize the "scroll" values of both text areas.
-
9
Type "});" and press "Enter" to close out of the "scroll" variable defining code. Type "});" again and press "Enter" to close out of the main script function.
-
10
Type "</script>" to close the scripting tags.
-
11
Click to place your cursor between the "<body>" and "</body>" tags and press "Enter" to create a blank line.
-
12
Type "<textarea id='textarea1' cols='20' rows='5'>" and press "Enter" to create the opening tag of the first text area.
-
13
Type the content that you want to appear in the first text area.
-
14
Type "</textarea>" to close the first text area tags.
-
15
Type "<textarea id='textarea2' cols='20' rows='5'>" and press "Enter" to create the opening tag of the second text area.
-
16
Type the content that you want to appear in the second text area.
-
17
Type "</textarea>" to close the second text area tags.
-
18
Click the "File" menu, then click "Save."
-
1