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,543
  • 3
  • 20
  • 32

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');
});
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
martynas
  • 12,120
  • 3
  • 55
  • 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,600
  • 1
  • 20
  • 26