YSbakker
YSbakker

Reputation: 707

Trying to remove a class with JavaScript, element doesn't take properties of other class

So whenever the scrollTop of my page reaches 1, it will automatically scroll down to another location on the page (this is demonstrated in the JSFiddle more clearly). This does work, but however trying to remove a class from a menu item (so that it becomes "unselected"), problems occur. The element doesn't seem to get the properties of the other class and shows as standard text (again, look at the JSFiddle for a demonstration). I was wondering how to fix this.

The following code is where my problems occur:

<div id="homeButton" class="menuItem selected">Home</div>
<div id="overButton" class="menuItem">Over</div>
<div id="contactButton" class="menuItem">Contact</div>
.menuItem {
    padding-top: 29px;
    height: calc(100% - 29px);
    border: 0;
    text-align: center;
    font-family: Signika;
    font-size: 25px;
    color: rgb(203, 207, 218);
}
.selected {
    border-bottom: 4px solid rgb(59, 89, 202);
    height: calc(100% - 33px);
    color: rgb(160, 170, 218);
}
var homeButton = document.getElementById("homeButton");
var aboutButton = document.getElementById("overButton");

homeButton.className = homeButton.className - " selected";
aboutButton.className = aboutButton.className + " selected";

Upvotes: 1

Views: 51

Answers (2)

vasilenicusor
vasilenicusor

Reputation: 2073

use this

$("#homeButton").removeClass( "selected" );
$("#overButton").addClass( "selected" );

instead of

var homeButton = document.getElementById("homeButton");
var aboutButton = document.getElementById("overButton");

homeButton.className = homeButton.className - " selected";
aboutButton.className = aboutButton.className + " selected";

Upvotes: 2

Preston Martin
Preston Martin

Reputation: 2963

You can add the menuItem class.

homeButton.className = homeButton.className - " selected";
homeButton.className = "menuItem";
aboutButton.className = aboutButton.className + " selected";

But I recommend that you remove and add classes with .removeClass() and .addClass() instead.

Upvotes: 0

Related Questions