justme justme - 3 months ago 8
HTML Question

I can't get multiple same ids to execute the same script

I want to create scroll-to-top buttons.

This is my code in JS. The problem is that even though I have 3 buttons with the same id I can only use only one everytime I load the page. Why is this happening? What should I do?

UPDATE

I didn't know that I could only use ID once. I tried all the suggested solutions but for some reason the getElementsByClassName doesn't work either. :(

The solution was to replace with:

$('.scrolltotop').on('click', function(){/* do your stuff */});


Here is my html too:

<ul class="stats">
<li class="scrolltotop"><a href="#">GO TO TOP</a></li>
</ul>


JS:

document.getElementsByClassName('scrolltotop').onclick = function () {
scrollTo(document.body, 0, 100);
}

function scrollTo(element, to, duration) {
if (duration < 0) return;
var difference = to - element.scrollTop;
var perTick = difference / duration * 2;

setTimeout(function() {
element.scrollTop = element.scrollTop + perTick;
scrollTo(element, to, duration - 2);
}, 10);
}

Answer

New code. This should work.

getElementsByClassName will only return you array-like object of all the elements having the class name. You have to loop it and assign it one by one.

var classData = (document.getElementsByClassName('scrolltotop'));
for(var i = 0; i < classData.length; i++)
{
    classData[i].onclick = function()
    {
        scrollTo(document.body, 0, 100);
    }
}
function scrollTo(element, to, duration)
{
    if(duration < 0) return;
    var difference = to - element.scrollTop;
    var perTick = difference / duration * 2;

    setTimeout(function()
    {
        element.scrollTop = element.scrollTop + perTick;
        scrollTo(element, to, duration - 2);
    }, 10);
}

Another way to do it easily is to use jQuery.

$('.scrolltotop').on('click', function(){/* do your stuff */});