I have a question regarding the use of the length of an array as an integer value in JavaScript. Here is the code snippet:
var counter = 0;
var bannerLinks = document.getElementsByClassName("bannerlink");
var linkCount = bannerLinks.length;
var clickCount = new Array(linkCount);
for (var i = 0; i < clickCount.length; i++)
clickCount[i] = 0;
function trackClicks(id) {
counter = clickCount[id];
counter++;
clickCount[id] = counter;
counter = 0;
alert("Total Links on Page: " + linkCount + "\nClick Count: " + clickCount[id] + "\nLink Identifier: " + id + "\nArray Size: " + clickCount.length);
}
The scenario is that I want to automatically set the size of the clickCount array based on the number of elements with the 'bannerlink' class found in my HTML. The functionality works if I manually assign a number to linkCount, but not when I use bannerLinks.length. Can anyone help me understand why it doesn't work in this context?
This script is designed to track clicks on href tags based on their assigned class. Although it's functioning somewhat better now after incorporating suggestions, there are still issues with incrementing the click count accurately. Any further tips or insights would be greatly appreciated.
An update from two hours later, following the advice provided, the script has improved slightly. However, the click counter isn't incrementing correctly. Below is the revised code. Thank you to everyone for your input and support thus far.
<script type="text/javascript">
var bannerLinks = document.getElementsByClassName("bannerlink");
var clickCount = [];
clickCount.length = bannerLinks.length;
function trackClicks(id) {
clickCount[id] = clickCount ? clickCount + 1 : 1;
alert("Total Links on Page: " + bannerLinks.length + "\nClick Count: " + clickCount[id] + "\nLink Identifier: " + id + "\nArray Size: " + clickCount.length);
}
</script>