function circleIndicator(){
for(let i=0; i< slides.length; i++){
const div=document.createElement("div");
div.innerHTML=i+1;
div.setAttribute("onclick","indicateSlide(this)")
div.id=i;
if(i==0){
div.className="active";
}
indicator.appendChild(div);
}
}
circleIndicator();
function indicateSlide(element){
index=element.id;
changeSlide();
updateCircleIndicator();
resetTimer();
}
*Why ‘this’ in indicateSlide(this)?
Hi @pandabuddy, this
always refers to the context on which a given method was called; in this case, it refers to the div
to which the onclick()
handler has been assigned. It may get clearer if you write it as an actual function, rather than an attribute string:
div.onclick = function () {
// We're assigning a function to the div's
// `onclick` property, so inside the function,
// `this` refers to `div`
indicateSlide(this)
}
Or better yet:
div.addEventListener('click', function () {
indicateSlide(this)
})
1 Like
Or better yet, get rid of the confusing this.
div.addEventListener('click', function (evt) {
const el = evt.target;
indicateSlide(el);
});
Edit:
evt.currentTarget is more appropriate in this case, giving code of:
div.addEventListener('click', function (evt) {
const el = evt.currentTarget;
indicateSlide(el);
});
2 Likes
Note though that event.target
will not necessarily be the same as this
, but might also be a child that dispatched the event; the exact equivalent to this
would be event.currentTarget
in this context.
1 Like
wow guys. You are amazing!
2 Likes