1

I'm new to JavaScript and have used the primary post about how to toggle classes from here: Change an element's class with JavaScript but for some reason my code is not executing like I would expect it to. The code is placed in the bottom of an HTML file.

<script>
$(document).ready(function () {

$('.arrow').addEventListener('click', function() {
if (this.hasClass('glyphicon-chevron-right')) {
    this.addClass('glyphicon-chevron-left');
    this.removeClass('glyphicon-chevron-right');
    }

if (this.hasClass('glyphicon-chevron-left')) {
    this.addClass('glyphicon-chevron-right');
    this.removeClass('glyphicon-chevron-left');
    }
}, false);

});
</script>
1
  • 7
    jQuery uses on to add events; not addEventListener Commented Jun 20, 2014 at 20:23

2 Answers 2

4

Set up a click listener and use .toggleClass() instead of those if clauses:

$('.arrow').on('click', function() {
    $(this).toggleClass('glyphicon-chevron-right');
    $(this).toggleClass('glyphicon-chevron-left');
});

Or more succinctly

$('.arrow').on('click', function() {
    $(this).toggleClass('glyphicon-chevron-right glyphicon-chevron-left');
});
Sign up to request clarification or add additional context in comments.

5 Comments

And even $(this).toggleClass("glyphicon-chevron-right glyphicon-chevron-left")
@JuanMendes i am aware of that. I though it would be more clear this way.
@martynas Now the OP is also aware of that ;)
Thanks guys, so I don't need to wrap this code in anything to make sure the document is ready? EDIT: Nevermind I figure it out, thanks again.
@WarGravy Yes, you should still make sure the document is ready. This snippet is just what needs to be changed from your original script
2

Just use the jQuery click event.

$('.arrow').click(function() {
    if (this.hasClass('glyphicon-chevron-right')) {
        this.addClass('glyphicon-chevron-left');
        this.removeClass('glyphicon-chevron-right');
    }
    if (this.hasClass('glyphicon-chevron-left')) {
        this.addClass('glyphicon-chevron-right');
        this.removeClass('glyphicon-chevron-left');
    }
});

if you want to add the event specifically with an event listener you would probably have to select the actual element instead of the jQuery object: $('.arrow')[0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.