Reputation:
if (btns.length && sections.length > 0) {
btns[0].addEventListener('click', function (event) {
smoothScrollTo(sections[0], event);
});
btns[1].addEventListener('click', function (event) {
smoothScrollTo(sections[1], event);
});
btns[2].addEventListener('click', function (event) {
smoothScrollTo(sections[2], event);
});
btns[3].addEventListener('click', function (event) {
smoothScrollTo(sections[3], event);
});
}
Hello friends lets say I have many more buttons! instead of coding each one of them how to make it in short! I am new in js...
Thanks
Upvotes: 2
Views: 1472
Reputation: 3581
You need to create an anonymous function to pass the i
variable.
if (btns.length && sections.length > 0) {
var l = btns.length;
for (var i = 0; i < l; i++) {
btns[i].addEventListener('click', function(event) {
(function(_i) {
smoothScrollTo(sections[_i], event);
})(i);
});
}
}
Upvotes: -2
Reputation: 405
I see a jQuery TAG over there, isn't it?
$(btns).click(function(event) {
smoothScrollTo(sections[$(this).index()], event);
});
It would be better if you add the index into the button as attribute, or with an ID, to prevent any problem...
Upvotes: 3