I have two divs, the two have the same id, target1
.
I need to get two divs in JavaScript and apply a function in the scroll event of div1
. This function will be responsible for getting the scroll value of div1
and apply it to the div2
scroll. The end result would be scrolling to div1
and div2
scrolling also accompanying div1
.
I was able to make it work by having the id's different, with target1
and target2
.
function scrollSincronizado(){
$( "#target1" ).scroll(function() {
$("#target2").animate(
{
scrollTop: $("#target1").scrollTop()+"px"
}, 0);
});
}
But as I need to consider that the two divs have the same id, then I got to that point:
function scrollSincronizado() {
var array = $('*[id*=target1]'); //Retorna um array com todos elementos com o id target1
var t1 = array[0];
var t2 = array[1];
//no console imprime o elemento com os dados completo
console.log(t1);
console.log(t2);
//nao executa a funcao no scroll da div, porque?
t1.scroll(function () {
console.log("entrou na funcao");
t2.animate({scrollTop: t1.scrollTop() + "px"}, 0);
});
}
This is the final test HTML:
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="123">
<div id="target1" onscroll="scrollSincronizado()" style="overflow: scroll; width: 200px; height: 100px;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.
</div>
</div>
<div id="456">
<div id="target1" style="overflow: scroll; width: 200px; height: 100px;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.
</div>
</div>
</body>
</html>
My questions are: