SkullDev SkullDev - 2 years ago 85
Javascript Question

class not being toggled on click

I have a navigation control containing links.

When a user clicks on a link, I want to toggle the class attribute of two links.

I want to assign a class of 'targeted' to the clicked link.

I also want to remove the 'targeted' class from the prior selected link.

here is my current es6 js.

$(() => {
//when one is clicked, remove the class from each of them and then add the class to the one that was clicked
$(document).on("click", ".tools-cover .tools-container > .row > .col-xs-12 > nav ul li a", (e) => {

$(document).find(".tools-cover .tools-container > .row > .col-xs-12 > nav ul li a").removeClass("targeted");



//when the page has loaded, click the first nav link on the nav
$(document).find(".tools-cover .tools-container > .row > .col-xs-12 > nav ul li:first-child a").click();

<div class="tools-cover">
<div class="container tools-container">
<div class="row">
<div class="col-xs-12">
<li><a href="#">Feeds</a>
<li><a href="#">Wearisma links</a>

Answer Source

Arrow functions don't have their own this, so jQuery cannot set it to the current element. You have to use a "normal" function as event handler, or use or e.currentTarget (not sure how well this works with event delegation) instead of this.

See also Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download