8

I would like to dynamically toggle a class on a click event on a div in Vue.js without using properties/data to do so.

Here is my div

<div class="quiz-item" @click="checkAnswer(1)">

When this div is clicked, I would like to add the class quiz-item--correct or quiz-item--incorrect (the logic for this will be handled elsewhere). I cannot use properties as there are too many answers in the quiz for it to be a maintainable/viable approach.

Does anyone have any ideas on how I can achieve this functionality?

1 Answer 1

23

You can do something like this:

<div class="quiz-item" @click="$event.target.classList.toggle('classname')">

You can check the fiddle demonstrating this: Here

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

4 Comments

i dont think classList is supported by all browsers, specifically IE
@victor Yeah, IE < 10 does not support the classList method. But you can use workaround if you want to support those browsers, like calling a function and manipulating classes there.
Hmm... kinda works... but sadly it didn't for me... Right now when in the div with this listener there is a span or another div or something. When I click on the element the child gets the open class. Not the element itself...
@LarsVandeDonk If you've nested elements within div which can receive clicks you might want to change the click handler to $event.currentTarget.class.... The target refers to the element where the event occurred which in your case can be any child element, currentTarget will refer to element where the event handler is bound. Hope this helps you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.