Add event listeners to arrays of elements and specify the target array of elements

window.onload = function() {
    // setting the default landing page to #Overview 
    window.location.replace("#Overview");
    // registering click event listeners for the top navigation bar:
    var navBarButtons = ["class1","class2","class3","class4","class5","class6","class7","class8","class9"];
    var navBarTargets = ["id1","id2","id3","id4","id5","id6","id7","id8","id9"];
    registerNavBar(navBarButtons, navBarTargets);
}
function registerNavBar(navBarButtons, navBarTargets){
    for (var i=0; i<navBarButtons.length; i++){
        sourceElement=document.querySelector("#left_nav .".concat(navBarButtons[i]));
        sourceElement.addEventListener("click",clickNavBarButton({targets:navBarTargets,index:i}))
    }
}
function clickNavBarButton(event){
    clearPages(event.targets);
    document.querySelector("#".concat(event.targets[event.index])).classList.add("active");
}
function clearPages(navBarTargets) {
    for (i=0; i<navBarTargets.length; i++){
        var target = "#".concat(navBarTargets[i]),classList=document.querySelector(target).classList;   
        if (classList.contains("active")){
            classList.remove("active")
        }
    }
}

Trying to implement onclick events on elements in the navigation bar with this structure:

<div id="left_nav">
                <a href="#Overview" title="Overview"><span class="class1"></span></a>

The registerNavBar() function is not successfully adding onclick events to the elements selected by #left_nav .classn. The definition of the .active class is:

.active {
    display: block!important
}

while the default state is:

display: none

therefore, toggling visibility. External libraries are not an option.

All functions in the loop are executing without errors and the element with #id9 is displayed, but the buttons do not trigger the onclick events when clicked. What is the correct way to add eventListeners to all elements in the Array?

Answer №1

To retain the event Object data, you have the option to create a closure.

function setupNavBar(navBarButtons, navBarTargets){
    for (var i=0; i<navBarButtons.length; i++){
        sourceElement=document.querySelector("#left_nav .".concat(navBarButtons[i]));
        sourceElement.addEventListener("click",handleNavBarClick({targets:navBarTargets,index:i}))
    }
}
function handleNavBarClick(event){
  return function(){
    clearPages(event.targets);
    document.querySelector("#".concat(event.targets[event.index])).classList.add("active");
    }
}

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

Retrieve all documents from PouchDB that match a specific regex pattern by their IDs

Is there a way to retrieve all documents with IDs that match a specific regex expression? Let's say we have the following document IDs: p0 p0/e0 p1 p1/e0 How do we only retrieve p0 and p1? Using the regex /^p[0-9]+$/. Currently, it takes two reque ...

Transferring data between Promises and functions through variable passing

I am facing a challenge. I need to make two separate SOAP calls in order to retrieve two lists of vouchers, and then use these lists to perform some checks and other tasks. I have placed the two calls within different Promise functions because I want to in ...

Can you explain the sequence of steps involved in setting up a server in node.js?

I'm curious about the order in which instructions are executed in this code. Specifically, I want to know if http.createServer() or server.listen is executed first, and when the callback function inside createserver will execute. const http = require( ...

Using React to Dynamically Display JSON Data as HTML

Struggling to incorporate HTML rendering from JSON data into my React component without relying on dangerouslySetInnerHTML. I want to include other React components within the rendered HTML, but facing challenges when trying to render multiple elements or ...

Tips for eliminating Ref upon exiting the screen on React / React Native?

When navigating back in React / React Native, I am encountering keyboard flickering caused by the presence of Ref on the screen. I would like to remove it before leaving the screen. The code snippet I am using is as follows: // To focus on the input fie ...

Having trouble with my JSFiddle code not functioning properly in a standard web browser for a Google Authenticator

Here is the code snippet that I am having trouble with: http://jsfiddle.net/sk1hg4h3/1/. It works fine in jsfiddle, but not in a normal browser. I have included the necessary elements in the head to call all the external files. <head> <scri ...

Overflowing issue with jQuery Show DIV disrupting footer of other DIVs

I have utilized jQuery to create a simple show/hide functionality. Currently, I am facing two issues: 1) The hidden DIV is displaying over the footer instead of causing the footer to drop down automatically. How can I achieve this? 2) Is there a way to h ...

Arranging string data in an array using JavaScript

I am faced with the task of merging and sorting two arrays containing string data: var AA = ["~/80/Blue/1.png","~/80/Blue/2.png","~/80/Black/1.png","~/80/Black/2.png"]; var BB = ["~/81/Blue/1.png","~/81/Blue/2.png","~/81/Black/1.png","~/81/Black/2.png"]; ...

Query Selector(jQuery selector) is a powerful tool for

Here is the HTML Table structure: <table class="display" style="width: 1000px;" id="failoverServers"> <thead> <tr> <th class="row_selector_head"> <input type='checkbox' class='select_all_ch ...

Having difficulty reaching elements within a shadow frame using Selenium in Java

I am encountering an issue while trying to access an element within a shadow iframe. I am able to switch to the frame successfully, but when attempting to access elements inside it, I am getting a Stale Element Exception. Any assistance with this would be ...

Each row in a table is filled with an array of data, with each column containing pdf

My goal is to split each associated element in every row of my PDF. Currently, the values are displayed below each column, as shown in the image below. packStruct = [] packEnergy = [] packDescriptionEnergy = [] packPrice = [] {text: 'Integration&apos ...

Tips for incorporating a live URL using Fetch

I'm having some trouble with this code. Taking out the &type = {t} makes it work fine, but adding it causes the fetch to not return any array. let n = 12 let c = 20 let t = 'multiple' let d = 'hard' fetch(`https://opentdb.com/ ...

Using regular expressions, eliminate the element from a JSON object that contains a specified property

Imagine I have a string representing a JSON object. It could be invalid, with some params that will be replaced by another system (e.g. %param%). The task at hand is to remove all objects with a known propertyName equal to "true" using regex. { "someT ...

Click on a React component to receive its property

Hey there! I'm currently in the process of developing an app that allows users to search for books and organize them onto specific shelves with just a click. Right now, users can type a query and see multiple results displayed on the screen. My goal i ...

The event 'deviceorientation' does not seem to be firing in iOS browsers when it is referenced within an iFrame

I am currently working on a website that features a "360 panorama viewer" embedded within an iframe. The source page utilizes JavaScript and window.DeviceOrientationEvent to determine if the user is browsing on a mobile device with orientation functionalit ...

Struggling to integrate Karma and Jasmine into my Angular controller setup

After numerous attempts and hours of troubleshooting, I am still unable to successfully integrate Karma with my Angular controller. No matter what I try, the same error persists even when removing expectGET() calls - as soon as $http.flush(); is called. A ...

Easy way to make a jQuery getJSON request to Twitter

After browsing through numerous Twitter and jQuery related questions, I have yet to find a solution to my specific issue. My goal is simple - to retrieve 5 "tweets" from a public user. At this stage, I am not manipulating the data in any way, but for some ...

Transforming a file with a node module that lacks a .js class into a browseable format

I am currently working on browserifying my module. One of the dependencies I have is on this https://www.npmjs.com/package/chilkat_win32. It is present in my node_modules folder and here is how the structure looks: https://i.stack.imgur.com/uw9Pg.png Upo ...

Error in code - message gets sent immediately instead of waiting for timeout to occur

There seems to be an issue with the code where the message is sent instantly instead of waiting for the specified timeout duration. Based on the code, it should wait for the time mentioned in the message. I'm puzzled as to why it's not functioni ...

The JSON data does not match the expected type (JSON.java:111)

I encountered an error org.json.JSON.typeMismatch(JSON.java:111) when attempting to create a JSON array. The data received is structured as follows: { "result":[ { "@type":"d", "@rid":"#-2:0", "@version":0, "a_adres":"kepez merkez geliyor h ...