Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How do i add an on click event to a class that was added?

Here is what I'm trying to achieve:

$(".journey-buttons__next").on("click", function() {
        $(".progress__bar span").css("width", "33.3%");
        $(".content__step-one").css("display", "none");
        $(".content__step-two").css("display", "block");
        $(".progress__completion").text("33% Complete");
        $(this).addClass("go-to-third-step");
});
$(".go-to-third-step").on("click", function() {
        $(".progress__bar span").css("width", "66.6%");
        $(".content__step-two").css("display", "none");
        $(".content__step-three").css("display", "block");
        $(".progress__completion").text("66% Complete");
        $(this).text("Complete");
});

1 Answer

Steven Parker
Steven Parker
229,982 Points

You could create a delegated handler in advance, but that would require a different approach to implementing the handler code.

The easiest fix would be to put the code that establishes the handler inside the other handler. And since the class is being added to "this", you could also skip the class setting entirely and just set the handler directly:

$(".journey-buttons__next").on("click", function() {
    $(".progress__bar span").css("width", "33.3%");
    $(".content__step-one").css("display", "none");
    $(".content__step-two").css("display", "block");
    $(".progress__completion").text("33% Complete");
    $(this).on("click", function() {
        $(".progress__bar span").css("width", "66.6%");
        $(".content__step-two").css("display", "none");
        $(".content__step-three").css("display", "block");
        $(".progress__completion").text("66% Complete");
        $(this).text("Complete");
    });
});