Problem with Javascript Tabs (cannot read property className of undefined)

Twine Version: 2.3.5
Story Format: Sugarcube

I got tabs working with some javascript and CSS, but when I try to highlight the active tab it throws me an error: cannot read property className of undefined).

Here’s some tab buttons:

  <button class="tablink" onclick="openTab(event,'Buy Stuff')">Buy Stuff</button>
  <button class="tablink" onclick="openTab(event,'Adjust Prices')">Adjust Prices</button>

Here’s some tab contents:

<<if $lastTab is "none">>
	<div id="Management Tab" class="tab">
		<<include "Management Tab">>
	</div>
<<else>>
	<div id="Management Tab" class="tab" style="display:none">
		<<include "Management Tab">>
	</div>
<</if>>

<div id="Buy Stuff" class="tab" style="display:none">
  <br>What would you like to buy?<br><br>
	<span id="buy"><<include "Buy List">></span>
</div>

<div id="Adjust Prices" class="tab" style="display:none">
	<span id="price"><<include "Price List">></span>
</div>

(It defaults to open the Management Tab unless you’re coming back from somewhere else)

And here’s the javascript (in the story javascript section):

window.openTab = function(evt, tabName) {
  var i, x, tablinks;
  x = document.getElementsByClassName("tab");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
	}
  tablinks = document.getElementsByClassName("tablink");
  for (i = 0; i < x.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" red", "");
  }
  document.getElementById(tabName).style.display = "block";
	evt.currentTarget.className += " red";
}

The problem is with getting the element by the “tablink” name. I don’t know anything about javascript and little about CSS, plus I got this from a W3.CSS website and adapted it. Soooo I have no idea, I’ve tried everything I can think of.

1 Like

I think this part is broken due to bad copy & paste.

tablinks = document.getElementsByClassName("tablink");
  for (i = 0; i < x.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" red", "");
  }

Instead of x.length, it should be tablinks.length. Fix that bit and see if it works. I haven’t tried any of the code so this is just me proofreading.

1 Like

Yep, that was it. I pasted new code over old code, so that’s where the mistake came from. Thanks!

1 Like