Reputation: 165
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
Reputation:
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
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
Reputation: 12052
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