I need some help with JavaScript, Bootstrap, and changing classes

I am using the Bootstrap .nav-tab class on a navigation list. I want to change it to a .nav-pill class under the 600px Media Query.

I got the classes each to load depending on the window width.

Now I’m shooting for pretty - I want the change to fire on the resize event.

I figured out how to get the classes to switch when I resize from wide to 600px, I cannot get it to go back.

Any suggestions?

Here is a link to my prototype:
http://www.craigwebbart.com/csw/links_switch_class_test_01.htm

Here is the JavaScript code that I have so far:

<script type="text/javascript">
if (window.matchMedia("(max-width: 600px)").matches) {
  /* the view port is at less than 600 pixels wide */
$("#myTab").addClass("nav-pills")
}
else {
  /* the view port is more than 600 pixels wide */
$("#myTab").addClass("nav-tabs");
};

window.onresize=function(){
	if (window.matchMedia("(max-width: 600px)").matches) {
  /* the view port is at less than 600 pixels wide */
$("#myTab").addClass("nav-pills")
}
 else {
  /* the view port is more than 600 pixels wide */
$("#myTab").addClass("nav-tabs");
}
};
</script>

Thank you in advance for any help.

You need to remove the class that you don’t want, so that when going from one to the other you don’t end up with both classes on the element.

Paul Wilkins you are a star!

With your advice I saw what I needed to do and now it works! YAY!

Here’s what I did:

  1. I got rid of the window.matchMedia. I don’t think that I need it, do I?
  2. I made a add/remove in the if / else declaration.

Here is the revised code:

<script type="text/javascript">
window.onresize=function(){
	if (window.matchMedia("(max-width: 600px)").matches) {
  /* the view port is at less than 600 pixels wide */
$("#myTab").addClass("nav-pills"),
$("#myTab").removeClass("nav-tabs")
}
 else {
  /* the view port is more than 600 pixels wide */
$("#myTab").addClass("nav-tabs");
$("#myTab").removeClass("nav-pills")
}
};
</script>

Thank you for your reply.

Wait! No I do need the window.matchMedia declaration.

I added it back in. Without it I get FLOUT and the navigation does not get a class until the window is resized.

Here is the code again:

<script type="text/javascript">
if (window.matchMedia("(max-width: 600px)").matches) {
  /* the view port is at less than 600 pixels wide */
$("#myTab").addClass("nav-pills")

} else {
  /* the view port is more than 600 pixels wide */
$("#myTab").addClass("nav-tabs");
};

window.onresize=function(){
	if (window.matchMedia("(max-width: 600px)").matches) {
  /* the view port is at less than 600 pixels wide */
$("#myTab").addClass("nav-pills"),
$("#myTab").removeClass("nav-tabs")
}
 else {
  /* the view port is more than 600 pixels wide */
$("#myTab").addClass("nav-tabs");
$("#myTab").removeClass("nav-pills")
}
};
</script>

And the test link:
http://www.craigwebbart.com/csw/links_switch_class_test_01.htm