0

After reading some questions/answers about this subject I have tried to make it works for me but I can't.

The story line is that I have X elements (so it means no ID just class) and I want to change the background when I click in one.

So with JS I did:

'click .switch' (event) {
    event.toElement.closest("li").css('background-color','black');


    if(this.stateMachine == 'running'){
      Meteor.call("switch", this.nameMachine);
    }

  },

to get the container (here a <li class="liMachine switch">) but I have this error:

event.toElement.closest(...).css is not a function

Despite the event.toElement.closest returns the right element: enter image description here

So what am I doing wrong ?

5
  • 2
    Change event.toElement to $(this) or $(event.target). Preferably the former Commented Mar 6, 2017 at 13:23
  • @RoryMcCrossan nothing happens, no error but no changes Commented Mar 6, 2017 at 13:25
  • What element is click in your selector? That's not valid HTML, unless you're using some odd library you haven't mentioned Commented Mar 6, 2017 at 13:25
  • It's with MeteorJS @RoryMcCrossan Commented Mar 6, 2017 at 13:26
  • It works with $(event.target) !! Commented Mar 6, 2017 at 13:31

2 Answers 2

4

$('.liContainer.switch').on('click', function() {
    $(this).toggleClass('active');
});
.active {
  background-color: powderblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="liContainer switch">one</li>
  <li class="liContainer switch">two</li>
  <li class="liContainer switch">three</li>
</ul>

If $(event.target) works for you then the problem was of course that you did not pass a jQuery object. So you can not use jQuery functions on non jQuery object.

Sign up to request clarification or add additional context in comments.

1 Comment

in the snippet it works but in my JS nothing happens (I putted some logs but nothing is displayed)
0

Since you are using Meteor, you may prefer this syntax:

"click .switch": function(event){
$(event.target).css("background-color", "black");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.