AnonUser AnonUser - 5 months ago 11
Javascript Question

toggleClass activating but not deactivating

My

toggleClass()
method activates when I click on a
.personId
, but it does not deactivate when I click on it again OR on a different
.personId
. What I am trying to do here is have the names of people, and when clicked on it shows their last name,
DOB
, etc. and then when clicked on again it disappears. Right now when I click on a name the information appears, but it does not disappear when clicked on again, or when a different
personId
is clicked on.

$(document).ready(function() {
$(".personId").on("click", function () {
var x = $(this).text();
$("." + x).toggleClass($(this).text());
});
});


<table class="personIdTable">
<tr><td class="personId">Bob</td></tr>
<tr><td class="personId">Bill</td></tr>
<tr><td class="personId">Tom</td></tr>
<tr><td class="personId">Jimmy</td></tr>
</table>
<h1 class="Bob"> BOB SMITH 04/12/1962 </h1>
<h1 class="Bill"> BILL SMITH 04/12/1962 </h1>
<h1 class="Tom"> TOM SMITH 04/12/1962 </h1>
<h1 class="Jimmy"> JIMMY SMITH 04/12/1962 </h1>


.Bob {
display: none;
}

.Bill {
display: none;
}

.Tom {
display: none;
}

.Jimmy {
display: none;
}

Answer

Issue: You doing this $("." + x).toggleClass($(this).text()); results in the class you are toggling being removed, and hence no longer to be found for toggling, eg: If you toggle '.Bill', 'Bill' class is removed from the element. Next time there is no Bill class to be found to add back the bill class (paradox?).

So instead of doing this:

.Bob {
    display: none;
}

.Bill {
    display: none;
}

.Tom {
    display: none;
}

.Jimmy {
    display: none;
}

You keep one class:

.hide {
  display: none;
}

Update your HTML:

<table class="personIdTable">
    <tr><td class="personId">Bob</td></tr>
    <tr><td class="personId">Bill</td></tr>
    <tr><td class="personId">Tom</td></tr>
    <tr><td class="personId">Jimmy</td></tr>
</table>
<h1 class="Bob hide"> BOB SMITH 04/12/1962 </h1>
<h1 class="Bill hide"> BILL SMITH 04/12/1962 </h1>
<h1 class="Tom hide"> TOM SMITH 04/12/1962 </h1>
<h1 class="Jimmy hide"> JIMMY SMITH 04/12/1962 </h1>

Note that I removed '.' from .Bob in the class name, because you don't need it in the html.

Update your js to do:

$(document).ready(function() {
    $(".personId").on("click", function () {
        var x = $(this).text();
        $("." + x).toggleClass('hide');
    });
});
Comments