Reputation: 10240
I have a small panel that slides out from the bottom. It has a chevron up icon. I am building a jquery snippet that bring it up (opens it) and closes it but all it must change the chevron from up to down.
The opening and closing is working and the chevron changes when it opens but it doesn't reset back to chevron up when it closes. Something is wrong in my conditional statement.
This is what I have so far
<script>
$("#openchat").click(function(){
$("#floatingmenu").toggleClass("chatbox-open");
if ($(this).hasClass("chatbox-open")) {
$(this).removeClass("fa-chevron-up");
$(this).addClass("fa-chevron-down");
} else if (!$(this).hasClass("chatbox-open")) {
$(this).addClass("fa-chevron-down");
$(this).removeClass("fa-chevron-up");
}
});
</script>
I am attaching a CODEPEN DEMO
BTW, my .chatbox-open class is what opens it and closes it. The other classes are simple font-awesome classes for the icons
Any help please
Upvotes: 1
Views: 331
Reputation: 136104
Your code only ever goes into the else
because #openchat
never has its classes toggled elsewhere.
You can just change to this
$("#openchat").click(function () {
$("#floatingmenu").toggleClass("chatbox-open");
$(this).toggleClass("fa-chevron-up fa-chevron-down")
});
Live example: http://codepen.io/anon/pen/myBeEb
Upvotes: 2
Reputation: 298
actually you don't need that check because if $(this).hasClass("chatbox-open")
is false it will go straight to else and execute it.
<script>
$("#openchat").click(function(){
$("#floatingmenu").toggleClass("chatbox-open");
if ( $(this).hasClass("chatbox-open") ){
$(this).removeClass("fa-chevron-up");
$(this).addClass("fa-chevron-down");
} else {
$(this).addClass("fa-chevron-down");
$(this).removeClass("fa-chevron-up");
}
});
</script>
just remove from else the if (!$(this).hasClass("chatbox-open"))
Upvotes: 0