Henk Z Henk Z - 2 months ago 5
Javascript Question

jQuery add class not working well

For some reason my code is not working, because it is not adding a class.

I want to add a class when clicking on the

<a>
and when clicking again it should be removed. When clicking again it should be added and so on.

What am I missing?

HTML:

<a class="show-specs" id="displayText" href="javascript:toggle();">Show specs</a>


Script:

<script language="javascript">
function toggle() {
var ele = document.getElementById("toggleText");
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
.addClass( "left-float" );
text.innerHTML = "Show specs";
}
else {
ele.style.display = "block";
text.innerHTML = "Hide specs";
}
}
</script>

Answer

You need to add a selector before a jQuery method like so:

$("#displayText").addClass( "left-float" );

The string "#displayText" means to select the element with the id "#displayText".

Although there is a better way to do this in jQuery by using .toggleClass() such as:

$("#displayText").click(function() {
    $(this).toggleClass("left-float");
});

Demo


Since you are using jQuery to attach an event handler replace the href with #:

<a class="show-specs" id="displayText" href="#">Show specs</a>