Utilize the size of the array as a variable

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>

Answer №1

If your intention is to have the clickcount variable filled with zeros, you can try the following approach:

Remove the existing code snippet:

var clickcount = new Array(linkcount);
for (var i = 0; i < clickcount.length; i++)
    clickcount[i] = 0;

And replace it with this alternative implementation:

var clickcount = [];
for(var i = 0; i < linkcount; i++){
    clickcount.push(0);
}

Answer №2

Instead of initializing the array to zero, you can simply leave it empty at first. This can be done by:

var clickcount = [];

Then, define a function like this:

function countClicks(id) {
    clickcount[id] = clickcount[id] ? clickcount[id] + 1 : 1;
}

When the click event occurs, if clickcount[id] is undefined (falsy), it will be assigned 1. Otherwise, it will be incremented by 1.

Your original code is also perfectly fine:

var bannercount = document.getElementsByClassName("bannerlink");
var linkcount = bannercount.length;
var clickcount = new Array(linkcount);
for (var i = 0; i < clickcount.length; i++)
    clickcount[i] = 0;

alert(clickcount);
<a class="bannerlink">link1</a>

<a class="bannerlink">link2</a>

<a class="bannerlink">link3</a>

<a class="bannerlink">link4</a>
If you run the above code snippet, it will alert 0,0,0,0, as expected.

Here's an example using my approach:

var bannercount = document.getElementsByClassName("bannerlink");
var linkcount = bannercount.length;
var clickcount = []

function countClicks(id) {
    clickcount[id] = clickcount[id] ? clickcount[id] + 1 : 1;
  alert(clickcount);
}

var links = document.getElementsByClassName("bannerlink");

for (var i = 0 ; i < links.length; i++) {
  links[i].addEventListener("click", function() {
      countClicks(this.id);
    });
  }
<a class="bannerlink" id="0">link1</a>

<a class="bannerlink" id="1">link2</a>

<a class="bannerlink" id="2">link3</a>

<a class="bannerlink" id="3">link4</a>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

My ReactNative Android application is experiencing significant lag, is there anyone who can assist me in resolving this issue?

Currently, I'm tackling a reactnative android app project and have noticed a significant drop in performance. Unfortunately, I am clueless about the root cause of this issue. Could it be related to the navigator or are there other underlying factors a ...

Unlocking the power of module augmentation in Typescript: Enhancing library models within your app domain

I currently work with two applications that share the same code base for their models. I am interested in developing and sharing a library model using inheritance in TypeScript. For instance, Pet extends Author. In my current Angular application, I need ...

The Jest mock for dates is completely ineffective and always ends up returning the constructor

beforeAll(() => { ... const mockedData = '2020-11-26T00:00:00.000Z' jest.spyOn(global, 'Date').mockImplementation(() => mockedData) Date.now = () => 1606348800 }) describe('getIventory', () => { ...

Updates to class variable values in jQuery are failing to take effect

Attempting to create my first JavaScript class has presented some challenges, specifically when it comes to updating a class variable. Despite hours of testing different approaches, I still can't seem to get it right! function ClassName(productId) { ...

Avoiding "Origin null is not allowed" error in Express.js POST request

I am attempting to send JSON data containing a set of key and values from JavaScript to Express.JS. Following advice from other posts, I have included the use of CORS and also added res.header("Access-Control-Allow-Origin", "*");. When testing the POST r ...

Leveraging the power of the underscore library within the WordPress

I'm currently utilizing the underscore library for handling arrays. I have included the library using the code snippet below in my functions.php file add_action( 'wp_enqueue_scripts', 'jt_enqueue_scripts' ); function jt_e ...

Incorporate dots into every slide using the React Slick slider

When implementing a slider in React.js, I use React Slick. The API provided by React Slick allows us to easily incorporate previous and next buttons on each slide using the Previous and Next methods. However, I am curious about how to achieve the same fun ...

Tips for effectively passing query string parameters in Angular

I am looking to make an HTTP request with parameters through a query For instance: URL: https://api/endpoint?d=1&value=2 ...

Send a property parameter to the Vue component

In my project using Vue and Laravel, I am trying to create a modal window with 2 tabs. The idea is to have two buttons, with each button linked to a specific tab that should open when clicked. These buttons are located in the blade template: <button ...

Please refrain from utilizing MUI - useGridRootProps outside of the DataGrid/DataGridPro component

When we click on "Filter" in the context menu of our DataGrid, we encounter this error. We are working on implementing a component hierarchy for the DataGrid as follows: MigrationJobTable.tsx: return ( <div data-testid='migrationJobTa ...

Discover the secret to instantly displaying comments after submission without refreshing the page in VueJS

Is there a way to display the comment instantly after clicking on the submit button, without having to refresh the page? Currently, the comment is saved to the database but only appears after refreshing. I'm looking for a solution or syntax that can h ...

Exploring the World of C Pointers and Arrays

Can someone please explain the meaning of this code snippet in C? MDMA_Sobel_In_Des.StartAddress = (void *) (&Sobel_In_Buf0[0]); I am particularly curious about the right-hand side statement. Why is the address of the variable not directly assig ...

Limit access to the server in Node.js by allowing loading only if the request is coming from another page and form POST variables are present

After searching for documentation without success, I have a question: Is there a way to prevent users from directly accessing my node.js server at website.com:3000? Currently, when a user visits my node.js website, it crashes the whole server and takes i ...

Utilizing the URLSearchParams object for fetching data in React

I've implemented a custom hook named useFetch: const useFetch = (url: string, method = 'get', queryParams: any) => { useEffect(() => { let queryString = url; if (queryParams) { queryString += '?' + queryParam ...

Using NodeJS and Express: redirection fails to load the specified endpoint

My current project involves a simple e-commerce web application running on localhost built with nodejs and express. Admins are required to register in order to gain access to functionalities such as adding, editing, and removing products from the product l ...

Is there a way in Typescript to convert an array of variables from class A to class B, where class B is an extension of class A?

Hopefully this question is unique, as I couldn't find anything similar. I have created a definition for Array<Tag>, but now I want to change it to Array<TogglableTag>. The only difference between the two classes is an additional property. ...

Secure login verification coupled with intuitive navigation features

Just starting out with react native and I've created a UI for a restaurant app. Now I'm working on converting all static components to dynamic ones. My first task is figuring out how to implement login authentication and then navigate to a specif ...

Watching for changes in a callback function - Angular 2

I'm currently working on implementing a callback function within a service class that needs to send data back to the component class. ChatComponent.ts export class ChatComponent implements OnInit { constructor( public _chatService : ChatService) ...

UI thread was blocked due to withProgress being invoked from an external library function

Currently enhancing an extension that is almost finished, but facing a challenge in adding visual cues for lengthy operations. Initially suspected a missing async/await in the code, but struggling to identify the cause. The progress indicator isn't di ...

An error occurred while trying to access the stored data at https://localhost:5000. The SSL protocol encountered

I am attempting to utilize an API to retrieve data and transfer it to MongoDB from my React application to the Node.js server, but I keep encountering an error message along with another issue in the console. https://i.stack.imgur.com/Bj4M6.png Despite e ...