John Henry
John Henry

Reputation: 165

.addClass to element adds a styling then removes, how do I fix

I have a code

var prev;
function addClass( classname, element ) {
    prev = cn;
    var cn = document.getElementById(element);

    $(cn).addClass("selected");
}

The element in the dom look like this:

<div class="arrowgreen">
    <ul>
        <li><a href="" onclick="addClass('selected','first')" id="first">Manager</a></li>
        <li><a href="" onclick="addClass('selected','second')" id="second" ">Planner</a></li>
        <li><a href="" onclick="addClass('selected','third')" id="third">Administrator</a></li>
    </ul>
</div>

For 'arrowgreen' I have a styling which changes the li styling on rollover and click. When an element is clicked on, I want to apply the 'selected' classname to the element. It does this for a split second and then reverts back.

The css looks like

.arrowgreen li a.selected{
    color: #26370A;
    background-position: 100% -64px;
}

Upvotes: 0

Views: 120

Answers (3)

user1823761
user1823761

Reputation:

Working jsFiddle Demo

In usage of $ in your code, I see that you are using jQuery. There is no need to set onclick internally. Let's jQuery handle it for you:

// wait for dom ready
$(function () {
    // when user clicks on elements
    $('.arrowgreen li a').on('click', function (e) {
        // prevent default the behaviour of link
        e.preventDefault();

        // remove old `selected` classes from elements
        $('.arrowgreen li a').removeClass('selected');

        // add class `selected` to current element
        $(this).addClass('selected');
    });
});

Upvotes: 2

Emil A.
Emil A.

Reputation: 3445

Similar way to do it:

(function ($) {

    $('.arrowgreen > ul > li > a').on('click', function (e) {

        e.preventDefault();
        $(this).addClass('selected').siblings().removeClass('selected');

    }); 

}(jQuery));

Upvotes: 0

Niccol&#242; Campolungo
Niccol&#242; Campolungo

Reputation: 12052

Working JSFiddle

There was an error in your HTML, a " that opened a new string after onclick.

var prev;

function addClass(classname, element) {
    var cn = document.getElementById(element);
    prev = cn; //does nothing useful really
    $(cn).addClass("selected");
}

<div class="arrowgreen">
    <ul>
        <li><a href="#" onclick="addClass('selected','first')" id="first">Manager</a>
        </li>
        <li><a href="#" onclick="addClass('selected','second')" id="second">Planner</a>
        </li>
        <li><a href="#" onclick="addClass('selected','third')" id="third">Administrator</a>
        </li>
    </ul>
</div>

Remember to include jQuery in your page!

There is a way to do this without jQuery anyway:

function addClass(classname, element) {
    var cn = document.getElementById(element);
    prev = cn; //does nothing useful really
    cn.className += " " + classname;
}

Upvotes: 0

Related Questions