If I wanted to use the following code on multiple DIV#ID, how do I do so without duplicating 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');
});
What I want to do is perform this not only on div1
, but also on div2
, div3
, div4
.
But as you note, scrollElem
is a global variable so I can't just stick all of this code in 1 function.
Meaning, to get this to work - I would have to do:
// 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');
});
That's copying and pasting a lot of duplicate code.
Question: there must be a better way to do this. Any ideas on how to accomplish the same functionality but minimize the duplication of code.