0

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

2
  • If your code is structured like in your question, it will never work... Commented Mar 15, 2017 at 15:00
  • Actually if you see the class added is maybe a specificity issue Commented Mar 15, 2017 at 15:00

3 Answers 3

1

Try this:

activeButton.removeClass('idleColor').addClass('redColor');
Sign up to request clarification or add additional context in comments.

Comments

1

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");

Comments

0

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.

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.