Y.G.J
Y.G.J

Reputation: 1108

Remove attr only if it was made with jquery

I have a menu that on mouseover will add attr class this. if a selected tab was selected and the page was reloaded with it, it has class this

I want that on mouseout I will be able to remove the added class only if it was the one I have just added and not the one that was load with the page - how can I?

Upvotes: 1

Views: 153

Answers (3)

aquinas
aquinas

Reputation: 23796

Several ways to do it. One way is to use data.

$("whatever").mouseover(function (){
  if (!$(this).hasClass("someClass")) {
    $(this).addClass("someClass").data("addedByMe",true);
  }
});

$("whatever").mouseout(function (){
   if ($(this).data("addedByMe") == true){
      $(this).removeClass("someClass");
   }
});

Upvotes: 2

rahul
rahul

Reputation: 187070

You can set a variable on page load.

var isClassAppliedAtLoad = false;

if ($("#yourelement").hasClass("yourclassname")) {
    isClassAppliedAtLoad = true;
}

and in your mouseover event you can check the variable.

Upvotes: 0

PeterWong
PeterWong

Reputation: 16011

I would suggest using two calss names (such as selected and focused).

So when you selected a tab, you add the selected class to it. The mouse over and out event alter the focused class only.

You could set both selected and focused to have the same CSS rule set or not if you want.

$(".menu-item").mouseover(function() {
  $(this).addClass("focused");
  // or if you don't want the effect affect the selected item, use the following:
  // if(!$(this).hasClass("selected")) { $(this).addClass("focused"); }
}).mouseout(function() {
  $(this).removeClass("focused");
});

Upvotes: 0

Related Questions