I'm having a problem with a simple tabbed page. It all works OK if I hard code the 'onclicks' in the tabs that appear at the top of the page like this:
<ul class="tabs" data-persist="true">
<li class='tablinks' onclick="openTab('view1')" id='default'>How to find Maolbhuidhe</li>
<li class='tablinks' onclick="openTab('view2')">How to get to Mull</li>
<li class='tablinks' onclick="openTab('view3')">Map of Mull</li>
<li class='tablinks' onclick="openTab('view4')">Map of Scotland</li>
</ul>
There's a JS file containing the function 'openTab', of course.
But when I try to add the onclick events via JS/jQuery after the page has loaded, I'm running into a problem. The HTML for this section now looks like this:
<ul id='toptabs' class="tabs" data-persist="true">
<li class='tablinks' id='default'>How to find Maolbhuidhe</li>
<li class='tablinks'>How to get to Mull</li>
<li class='tablinks'>Map of Mull</li>
<li class='tablinks'>Map of Scotland</li>
</ul>
The JS script I'm using to add the onclick events is:
function applyClicks() {
var toptabs = document.getElementById("toptabs");
var lnks = toptabs.getElementsByTagName("li");
for (var i=0; i<lnks.length; i++) {
var k = (i+1)
var vw = 'view' + k;
alert ('vw is: ' + vw);
lnks[i].onclick = (function() {
openTab('view' + k);
});
}
}
The problem seems to lie in providing the parameter to 'openTab()'. I've tried several variations, the one shown ends up as "openTab('view' + k)" (As seen in Inspector DOM). If I hard code it as 'view1' it works, but of course all the links are then the same, so only the first tab can be shown. It seems whatever I put in the JS function as the parameter gets treated as a literal.
What do I need to do to make the parameter 'view1', 'view2', 'view3', 'view4' (as in the hard coded version) according to the value of i ? This was the purpose of the var 'vw', which duly shows all the right values in turn as the script runs, but just shows up in the link on the page as 'vw'
I've also tried the widely recommended 'addEventListener('click', ...) etc. but I get the same problem (or something similar). It may be better to add an event listener eventually, but first I need to resolve the problem of passing the variable to the 'Click'.