Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  159] [ 6]  / answers: 1 / hits: 20721  / 8 Years ago, fri, february 26, 2016, 12:00:00

I want to change a class when I click.



The class is icon icon_plus, and when i click i want that class to be icon icon_minus-06and if click again back tothe original



My HTML code



<a href=# id=top-bar-trigger class=top-bar-trigger><i id=icon    class=icon icon_plus></i></a>


My javascript code :



<script>
$(a.top-bar-trigger).click(ontop);
function ontop() {

$(#icon).toggleClass(icon icon_minus-06);
}
</script>


I am very weak with javascript



Thanks for the help.


More From » jquery

 Answers
50

Try to write toggleClass like this,



$(#icon).toggleClass(icon_plus icon_minus-06);


Since you are keeping icon class as a static one.



DEMO



Also as a side note, try to wrap your code inside document's ready handler. Since the selector would fail, if you keep your script inside header tag. But If you have placed your script in the end of body tag, then no issues. Anyway its better to use document's ready handler as it would make the code more procedural.



The code should be like this,



(function(){
function ontop() {
$(#icon).toggleClass(icon_plus icon_minus-06);
}
$(function(){
$(a.top-bar-trigger).click(ontop);
});
})();

[#63146] Wednesday, February 24, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
agustindejonm

Total Points: 738
Total Questions: 84
Total Answers: 84

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
agustindejonm questions
Fri, Jun 25, 21, 00:00, 3 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Sat, May 16, 20, 00:00, 4 Years ago
;