Andrew Nguyen Andrew Nguyen - 4 months ago 7
Javascript Question

Calling a function inside click handler, not running

Problem



I'm calling the function
resetSelection
that should remove
.is-active
classes and add a class of
is-inactive
to a list of hockey players, amongst other things, after the submit button
.btn--submit
has been clicked.

Right now, the
.is-active
classes remain on the picked players and the function does not run?

index.html



<button class="btn btn--submit"><img src="src/img/ballot-alt.png" class="image--ballot">Submit Vote</button>


scripts.js



function resetSelection() {
$(".btn--reset").on("click", function(){
$(".picked").removeClass("is-active");
$(".picked").addClass("is-inactive");
$(".icon-checkmark").removeClass("is-completed");
$(".btn--submit").hide();
$(".btn--submit").removeClass("slideLeft");
starredGoaltenders = 0;
starredDefencemen = 0;
starredForwards = 0;
console.log(starredGoaltenders, starredDefencemen, starredForwards);
});
} resetSelection();

$(".btn--submit").on("click", function(){
console.log("Clicked");
resetSelection();
});

Answer

Your function binds a click handler event to elements with the class btn--reset. Consider refactoring resetSelection to include the logic within that event handler, but not the event handler itself:

function resetSelection() {
    $(".picked").removeClass("is-active");
    $(".picked").addClass("is-inactive");
    $(".icon-checkmark").removeClass("is-completed");
    $(".btn--submit").hide();
    $(".btn--submit").removeClass("slideLeft");
    starredGoaltenders = 0;
    starredDefencemen = 0;
    starredForwards = 0;
    console.log(starredGoaltenders, starredDefencemen, starredForwards);
}

$(".btn--reset").on("click", resetSelection);

$(".btn--submit").on("click", function(){
    console.log("Clicked");
    resetSelection();
});