War Gravy
War Gravy

Reputation: 1683

Trying to apply classes on a click event using JS

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>

Upvotes: 1

Views: 68

Answers (2)

martynas
martynas

Reputation: 12300

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');
});

Upvotes: 4

James McDonnell
James McDonnell

Reputation: 3710

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]

Upvotes: 2

Related Questions