Orionis
Orionis

Reputation: 1011

Changing class from Javascript/JQuery

I want to change a menu button in a page when it selected. No problems: I wrote (just using an example):

In CSS:

.idleColor{background:#0f0; ... }
.redColor {background:#f00;} 

In HTML:

<input id='m3' type=button class=idleColor>
....
<script>  /* at page end */
  $(document).foundation();
  ....
  var activeButton = $("#m"+menuId); //assuming menuID=3
  activeButton.addClass("redColor");    
</script>

This should replace the button background color from the idle color to the active one...simple, but not working.

Two strange things: with Firebug I see that the class is added, both in 'className' and in 'classList', but the new color does not come up (and I do not thing I should reflow the button).

The other odd thing is that if I use $("#myID").classList.add("redColor") I get an error saying: myID.classList is undefined (?)

Environment:
Foundation Site 6
JQuery: jquery-2.2.4

Upvotes: 0

Views: 93

Answers (3)

Orionis
Orionis

Reputation: 1011

I want to sink into shame :-(

The main problem (class not changing) was due to a stupid, stupid, stupid error.

In my page I have two set of menus, for small or medium-up screens.

I copied the relevant parts of buttons in each section...with the same IDs !

The jQuery function did its job, selecting the correct button in the 'small' section (the first occurence it found), actually hidden.

Since I was testing with a large screen I did not see any change.

As far as the 'classList' problem, I forgot that it is an array, so it needs an index. Setting $("#myID")[0] fixed it.

Thanks to fauxserious to have clarified this. Now it works in both ways, javascript and jQuery.

This time I learned something too: when you are sure that the code is correct, look for the problem elsewhere.

Upvotes: 0

Donnie D&#39;Amato
Donnie D&#39;Amato

Reputation: 3940

You are confusing native JavaScript methods with jQuery ones.

The following problem...

$("#myID").classList.add("redColor") I get an error saying: myID.classList is undefined (?)

..occurs because classList is not a property of jQuery, it's a property of HTML Element Objects found in native JavaScript. This can be resolved in one of the following ways.

jQuery only

$("#myID").addClass("redColor");

JavaScript / jQuery hybrid

$("#myID")[0].classList.add("redColor");

JavaScript only

document.getElementById('myId').classList.add("redColor");

Upvotes: 1

Theo Orphanos
Theo Orphanos

Reputation: 1447

Try this:

activeButton.removeClass('idleColor').addClass('redColor');

Upvotes: 1

Related Questions