JQuery/Javascript - how to minimize duplicated code?
<p>If I wanted to use the following code on multiple DIV#ID, how do I do so without duplicating code</p>

<pre><code>var scrollElem = $('#div1');
scrollElem.scroll(function() {
 /* find the closest (hlisting) home listing to the middle of the scrollwindow */ 
    var scrollElemPos = scrollElem.offset();
    var newCenter = $(document.elementFromPoint(
        scrollElemPos.left + scrollElem.width()  / 2,
        scrollElemPos.top  + scrollElem.height() / 2)
    ).closest('.hlisting');
    if(newCenter.is(".HighlightRow")) return;
    $('.HighlightRow').removeClass("HighlightRow");
    newCenter.addClass('HighlightRow');
});            
</code></pre>

<p>What I want to do is perform this not only on <code>div1</code>, but also on <code>div2</code>, <code>div3</code>, <code>div4</code>.</p>

<p>But as you note, <code>scrollElem</code> is a global variable so I can't just stick all of this code in 1 function.</p>

<p>Meaning, to get this to work - I would have to do:</p>

<pre><code>// DIV 2 ---------------------------
var scrollElem2 = $('#div2');
scrollElem.scroll(function() {
 /* find the closest (hlisting) home listing to the middle of the scrollwindow */ 
    var scrollElemPos = scrollElem2.offset();
    var newCenter = $(document.elementFromPoint(
        scrollElemPos.left + scrollElem2.width()  / 2,
        scrollElemPos.top  + scrollElem2.height() / 2)
    ).closest('.hlisting');
    if(newCenter.is(".HighlightRow")) return;
    $('.HighlightRow').removeClass("HighlightRow");
    newCenter.addClass('HighlightRow');
});

// DIV 3 ---------------------------
var scrollElem3 = $('#div3');
scrollElem3.scroll(function() {
 /* find the closest (hlisting) home listing to the middle of the scrollwindow */ 
    var scrollElemPos = scrollElem3.offset();
    var newCenter = $(document.elementFromPoint(
        scrollElemPos.left + scrollElem3.width()  / 2,
        scrollElemPos.top  + scrollElem3.height() / 2)
    ).closest('.hlisting');
    if(newCenter.is(".HighlightRow")) return;
    $('.HighlightRow').removeClass("HighlightRow");
    newCenter.addClass('HighlightRow');
});
</code></pre>

<p>That's copying and pasting a lot of duplicate code.</p>

<p><strong>Question</strong>: there must be a better way to do this. Any ideas on how to accomplish the same functionality but minimize the duplication of code.</p>
