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>
Community
  • 1
  • 1
War Gravy
  • 1,383
  • 3
  • 18
  • 28

2 Answers2

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');
});
Juan Mendes
  • 85,853
  • 29
  • 146
  • 204
martynas
  • 11,924
  • 3
  • 52
  • 60
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]

James McDonnell
  • 3,502
  • 19
  • 25