I am migrating a piece of code that I have in jquery. It is the following:
$(window).scroll(function() {
var ele = document.getElementById('holamundo');
if(esVisible(ele)== true){
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({ countNum: $this.text()}).animate({
countNum: countTo
},
{
duration: 2000,
easing:'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
}
});
});
}else{
}
});
function esVisible(elem){
var posTopView = $(window).scrollTop();
var posButView = posTopView + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).outerHeight();
return ((elemBottom < posButView && elemBottom > posTopView) || (elemTop >posTopView && elemTop< posButView));
}
So far I have managed to get the following done:
window.onscroll = function() {
const ele = document.getElementById('holamundo');
if(esVisible(ele)== true){
document.getElementsByClassName('counter').foreach( function(element){
countTo = element.getAttribute('data-count');
});
}else{
}
};
but it throws me an error in foreach:
uncaught TypeError: document.getElementsByClassName(...).forEach is not a function
So far this causes me conflict.
If I'm not mistaken, you get the error because you are trying to iterate through a non-iterable object, it has to be an array or json , I see this when obtaining the elements with class counter .
Change:
getElementsByClassName('counter')
By:
querySelectorAll('.counter')
This generates an iterable object and you can iterate through it.
This happens because it
document.getElementsByClassName()
returns aHTMLCollection
, not an array.If you really want to use
document.getElementsByClassName()
, you can convert the result to an array:Array.from()
,For case 1:
and case 2:
From this, you will be able to use the
forEach()
.As other alternatives, you can do what is mentioned in the other answers, such as simply using a
for
or making use ofquerySelectorAll()
, which returns aNodeList
, which itself is iterable.getElementsByClassName returns an HTMLCollection which does not have a foreach function.
You can do the following:
either