3
I have two Ivs, both have the same id, target1
.
I need to take two Divs in Javascript and apply a function in the scroll event from div1
. This function will be responsible for picking up the value of the scroll div1
and apply in the scroll of div2
. The end result would be to scroll to div1
and the div2
scrollar also accompanying the div1
.
I managed to make it work by having different id’s, with target1
and target2
.
function scrollSincronizado(){
$( "#target1" ).scroll(function() {
$("#target2").animate(
{
scrollTop: $("#target1").scrollTop()+"px"
}, 0);
});
}
But since I need to consider that the two Divs have the same id, then I’ve come to this 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 doubts are:
- What am I doing wrong?
- How could I catch these two Divs and make these Scrolls synchronized by Javascript?
Luan, it is incorrect to use the same
id
in more than one div. Use class instead.– Sam
Why it is considered wrong/bad to repeat an HTML ID?
– Guilherme Nascimento
Yes, I know it’s wrong, but unfortunately in the scenario I have here, I can’t change that. I tested using class as suggested but the result was the same without success.
– Luan Froehlich