Issue encountered in the tabs section: Upon clicking a tab, an error arises indicating that the style property

Seeking to implement a tab section where clicking on a tab reveals content below. I have utilized the code provided in the following CodePen, but encountering an error.

`

Uncaught TypeError: Cannot read properties of undefined (reading 'style')

`

Puzzled by the issue with the logic and why the 'style' property is inaccessible resulting in an error when clicking on a tab.

CodePen Link: https://codepen.io/theSpaceWeasel/pen/XWBKdbP?editors=1111

`

var btns = document.querySelectorAll(".tablinks");
console.log(btns);
var content = document.querySelectorAll(".tabcontent");
console.log(content);

for(var i=0; i<btns.length;i++){
  btns[i].addEventListener('click', function(){
    content[i].style.display = "block";
  })
}


`

Answer №1

The challenge presented in the initial code arises from the fact that the content[i] element is recognized as undefined when the event listener callback function is triggered. This occurs because the reference to i reflects its final value at the conclusion of the loop, which is consistently greater than anticipated.

for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", (function(index) {
    return function() {
      content[index].style.display = "block";
    };
  })(i));
}

In order to address this issue, one potential solution involves implementing a closure to establish a distinct scope for each iteration within the loop. By doing so, a new instance of the variable i can be created, enabling access to the appropriate element within the content array when triggering the event listener callback function.

An alternative approach would be to store the current content element in a variable like:

for (var i = 0; i < btns.length; i++) {
  const ele = content[i];
  btns[i].addEventListener("click", (function() {
      ele.style.display = "block";
  }));
}

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

Displaying a profile hover card allows users to easily discover and choose whether to follow or explore

I created a profile hover card on my website with a follow/unfollow button. However, I encountered an issue - the hover card disappears when I move away from my profile thumbnail. How can I fix this so that the hover card stays visible on mouseover and dis ...

Ways to show notifications multiple times depending on the number of items in a list

My task is to show banner messages on the user interface based on the number of items in a list. In my _Layout file, I called my partial view like this: @Html.Partial("~/_Notification.cshtml") The content of _Notification.cshtml: <div id="outage- ...

Transmitting occasional feedback from ASP.NET Web API function to jQuery AJAX

I am currently working on a project that requires sending intermittent status responses from a Web API method back to a jQuery AJAX call in order to display progress in the UI. https://i.sstatic.net/Y6R4w.png The process involves the jQuery AJAX calling ...

The jQuery function text().replace('','') is failing to work properly

After spending countless hours attempting to remove a text string that I previously appended, I am still struggling. The script I have is responsible for managing an accordion and unfortunately contains some redundant text. My goal is to add and remove th ...

Guide to creating a simple multi-column index linking each item to a specific page reference

Here's an idea I have in mind: Alan 12 | Byron 104 Alfred 54 | Charles 33 Ann 28 | Cleopatra 7 Basil 133 | Corey 199 ...

Exploring nested maps in JavaScript

I attempted to nest a map within another map and encountered an issue where the innermost map is being executed multiple times due to the outer map. The goal is to link each description to a corresponding URL (using # as placeholders for some links). Here ...

Troubleshooting Problem with Passing Array Data to PHP using $.post

I am encountering an issue when attempting to send an array of objects to the server via POST using Ajax with JQuery version 1.10.2. The array I am sending consists of objects which are essentially associative arrays. When I use the function JSON.stringif ...

What is the best approach to retrieve a username from a SQL database using AJAX within a Flask application

I have been attempting to retrieve the username column information from SQL using ajax, but only the username of the first ID is being returned. However, I need all usernames to be fetched. Below is the model: class users(db.Model): id=db.Column(db.I ...

form_not_submitting_ajax

In the app I'm working on, I have a form that is defined in the following manner: = form_with model: project, remote: true, method: :put do |f| = f.select :selected_draw, options_for_select(project.draws.pluck(:number, :id), draw.id), {}, class: &a ...

Utilizing KnockoutJS Binding Multiple Times Throughout a Web Page

When using KnockoutJS with an external template, it is necessary to wait for the template to load before applying the ViewModel bindings. This means that if the template fails to load, none of the elements on my page will be bound to knockout. Is there a w ...

What is the purpose of calling Array.prototype.filter on the 'forms' array with the function(form)?

I'm struggling to grasp the inner workings of this code snippet. It appears to be a piece of form validation code taken from Bootstrap and pasted here. My confusion arises from this line var validation = Array.prototype.filter.call(forms, function(f ...

Load link dynamically using the rel attribute

I am trying to implement dynamic content loading using jQuery's .load() function. The links are stored in the .rel attribute of the anchor tags. My setup looks like this: <script> $(document).ready(function(){ $('.sidebar_link').clic ...

producing a NaN result when calling a reducer with an integer value

Could anyone assist me with this react-redux code? I have an input field that accepts numbers and adds them to the counter above. My goal is to reset the counter to 0 if the input is not a number, but currently when I type any character other than an int ...

Having trouble accessing a gtlf file in an HTML document using Three.js

My goal is to create an interactive and clickable 3D image that I downloaded from Sketchfab using Three.js. I have carefully followed the guidelines provided by ChatGPT and have all the necessary scripts in my folder (GLTFLoader.js, main.js, OrbitControls. ...

Launching a Node.js command-line interface to NPM, developed using TypeScript

I'm struggling with deploying my Node CLI tool to NPM. During development and testing, everything works fine. I can even use `npm link` on the repo without any issues. After successfully publishing and downloading the package, the application crashes ...

Having trouble with parsing JSON data using jQuery?

I am currently working on retrieving a result set using postcodes with jQuery autocomplete. However, the code I have implemented seems to be displaying an empty set of rows. <html lang="en"> <head> <meta charset="utf-8> <title>Ausp ...

Substitute the ajax reply with the text currently displayed

I am facing an issue with the AJAX response in my HTML page. Currently, the response is being appended on top of the existing text instead of replacing it. Here is a snippet of my code: <html> <head> <h2>This is a test</h2> ...

Maintaining a value upon submission

I have been struggling with this issue for a few days. Initially, I was confused and looking into using code for a postback and storing my value in a hidden field. However, upon further investigation, it appears that the solution involves simply using a "d ...

Center an image vertically within its container

Here is an example of some HTML/CSS code: .section { width: 100%; height: 200px; overflow: hidden; } .section img { max-width: 100%; height: auto; } <div class="section"> <img src="http://www.example.com/image.jpeg" alt="image" /> ...

It seems like there may be an issue with the npm UNMET PEER DEPENDENCY message

After attempting to npm install simple-react-bootstrap-navbar in my current project, I encountered an issue. The project itself has react 15.1.0 listed as a dependency. Interestingly, the simple-react-bootstrap-navbar package specifies "react": ">=0.1 ...