Add class to the parent element on hover

Hello all,

I need to add class to the parent element when hovering its child. I solved it by taking the event target parent and assigning class to it by changing html using ‘classList.add’ and ‘classList.remove’.

Later I learned that its actual bad practice… It works, but I just don’t know how to solve using pure VueJs principles.

Here is fiddle with example:
https://jsfiddle.net/artrayd/t8frod6p/

Any help is highly appreciated :pray:

Two comments:

In getHoverBut I would use

	  getHoverBut:function(index){
    	// coorect way
			this.activeTabIndex = index; // no -1
    },

and then in the call @mouseover="getHoverBut(index)". This way you can omit the tab-Value which only in the case of your example data maps to index+1.

I would also use the index as parameter to @mouseover="closeHov($event)" which then would be @mouseover="closeHov(index)". @mouseleave="closeOut()" does not need a parameter. In closeHov() and closeOut() I would directly set this.activeTabIndex as in getHoverBut().

1 Like

Thank you fiedsch,

According to the first comment:
Yes, you are absolutely right, that was my error.

According to the second comment, the issue is that I need to use different class “active” class for close button mouseover. It supposed to be ‘closeAct’ and I have no idea how to write it correctly…

// I tried this one, but it didn't work, maybe because syntax is wrong..
{ active: index === activeTabIndex || closeAct: index === closeTabIndex }

Maybe I should use here computed property instead? Like if mouse is over close tab, so return ‘closeAct’?

Looks like you are missing the this. on activeTabIndex.

@fiedsch that’s because it’s part of html code, should I add this there?

:class="{ conditional code that I don’t know how to write }"

OK, then it should be

{ active: index === activeTabIndex, closeAct: index === closeTabIndex }

see https://vuejs.org/v2/guide/class-and-style.html#Object-Syntax

1 Like

Thank you a lot! It worked!

Also I figured out, if I want to add one conditional and one static class, so I need to add like two html parameters, like

  <li
  v-for="(tab, index) in tabs"
  class="staticClass"
  :class="{ dynamicClass: index === activeTabIndex}">

You could also make it

<li
  v-for="(tab, index) in tabs"
  :class="{ staticClass: true, dynamicClass: index === activeTabIndex}">

but I’m not sure if that should be considered good style.

1 Like

Thank you, That worked just fine! I prefer this than having two class parameters :slight_smile: