Can I get a number inside a square?
What I would like is when I click on the demo button it alerts me with a number inside a green (highlighted) square.
$('#demo').click(function() {
var x = document.getElementsByClassName('selected');
var numb = x[0].innerHTML;
alert(numb);
});
The problem is that I always get "1" as results and this is not what is expected ...
Thanks for your help!
This is because you < remove the class selected
when you scroll up , otherwise it will keep the class.
When using JavaScript console
document.getElementsByClassName('selected');
[<li class=β"post selected">β1β</li>β,
<li class=β"post selected">β2β</li>β,
<li class=β"post selected">β3β</li>β,
<li class=β"post selected">β4β</li>β,
<li class=β"post selected">β5β</li>β]
You need to either fix your logic to remove all other classes selected
when adding a new one.
Or you can just select the last selected as I did in the following example using x.length - 1
var x = document.getElementsByClassName('selected');
var numb = x[x.length - 1].innerHTML;
source to share
You get what you ask for.
On scrolling, you add a class .selected
to each li
one that exits the viewport. So when you do document.getElementsByClassName('selected')
, you end up with an array of DOM objects, which you always refer to first. Open the latter instead :
var x= document.getElementsByClassName('selected');
var numb = x[x.length-1].innerHTML;
source to share