Steven M. Steven M. - 1 month ago 11
Javascript Question

Set CSS property with js click event handler

I am trying to create an onclick event which will show/hide elements of an array however I am struggling with the showSubTabGroup() function below.

Sidenote: Eventually I would like to make this onmouseenter and onmouseleave, rather than 'click' as you see below.

I would like to be able to click on a div and show subsequent div's below as you might expect from a navigation feature.

The console is not returning any errors, howver the 'click' function seems alert("CLICKED") properly.

Any help would be greatly appreciated.

Problem:

Tab.prototype.showSubTabGroup = function (tabIndex, subTabIndex) {
this.tab[tabIndex].addEventListener('click', function () {
alert("CLICKED");//Testing 'click' call
for (var i = subTabIndex; i < this.subTabGroup; i++) {
this.subTab[i].style.display = "";
}
});
}


Javascript:

function Tab (subTabGroup) {
this.tab = document.getElementsByClassName("tab");
this.subTab = document.getElementsByClassName("sub-tab");
this.subTabGroup = subTabGroup;
}

Tab.prototype.hideSubTabs = function () {
for (var i = 0; i < this.subTab.length; i++) {
this.subTab[i].style.display = "none";
}
}

Tab.prototype.showSubTabGroup = function (tabIndex, subTabIndex) {
this.tab[tabIndex].addEventListener('click', function () {
for (var i = subTabIndex; i < this.subTabGroup; i++) {
this.subTab[i].style.display = "";
}
});
}

var tab = new Tab(3);
tab.hideSubTabs();
tab.showSubTabGroup(0,0);


HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Responsive Nav</title>
</head>
<body>
<!-- JQuery CDN -->
<script src="http://code.jquery.com/jquery-3.1.0.js"></script>

<div class="container">
<div class="tab">
<p>TAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
</div>

<div class="container">
<div class="tab">
<p>TAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
</div>

<div class="container">
<div class="tab">
<p>TAB</p>
</div>
<div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
</div>
</div>

<script type="text/javascript" src="tab.js"></script>
<script type="text/javascript" src="tabEvents.js"></script>

</body>
</html>

Answer

The problem of what is this inside the click. It is not your tab code, it is the reference to the element that you clicked on. You need to change that by using bind

Tab.prototype.showSubTabGroup = function (tabIndex, subTabIndex) {
  this.tab[tabIndex].addEventListener('click', (function () { 
    for (var i = subTabIndex; i < this.subTabGroup; i++) {
      this.subTab[i].style.display = "";
    }
  }).bind(this));
}