September 21, 2009

Synchronize Scrolling of Two TextArea or Multiline ASP.NET TextBoxes using jQuery


The technique shown below synchronizes the scrolling of TextBox (tb2) with TextBox (tb1). As the user scrolls through the contents of tb1, the contents of tb2 is automatically scrolled to keep up with the display of tb1. The code shown here fits a requirement where two versions of the same document are to be compared with each other and the user need not have to explicitly scroll through both the textboxes to compare them.

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Sync two Multiline TextBoxes</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$('textarea[id$=tb1]').scroll(function() {
$('textarea[id$=tb2]')
.scrollTop($('textarea[id$=tb1]').scrollTop());
});
});
</script>
</
head>
<
body>
<
textarea id="tb1" cols="20" rows="2">
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
</textarea>
<
textarea id="tb2" cols="20" rows="2">
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
</textarea>
</
body>
</
html>

Note: You can also access the contents of the textarea using $(‘#tb1’) instead of $('textarea[id$=tb1]').

ASP.NET Multiline TextBoxes

The same code also works for two ASP.NET Multiline Textboxes

<html xmlns="http://www.w3.org/1999/xhtml">
<
head id="Head1" runat="server">
<
title>Sync two Multiline TextBoxes</title>

<
script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
</
script>

<
script type="text/javascript">
$(function() {
$('textarea[id$=tb1]').scroll(function() {
$('textarea[id$=tb2]')
.scrollTop($('textarea[id$=tb1]').scrollTop());
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:TextBox ID="tb1" runat="server" TextMode="MultiLine"
Text="Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum" />
<
asp:TextBox ID="tb2" runat="server" TextMode="MultiLine"
Text="Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum" />
<
br />
</
div>
</
form>
</
body>
</
html>

See a Live Demo

Others Also Read..

comments

0 Responses to "Synchronize Scrolling of Two TextArea or Multiline ASP.NET TextBoxes using jQuery"
 

Copyright 2010 All Rights Reserved DevCurry.com by Suprotim Agarwal