SoSnA5115 SoSnA5115 - 1 month ago 7
Javascript Question

jQuery Click event doesn't work when I add a Class before

I found this question but the solution is not working for me:
jQuery click event not working after adding class

I have this code:

$('.play_button i').click(function() {
$('.content').css( "background-position-x", "-800px" );
$(this).addClass('first_section');
});

$( '.play_button i.first_section' ).on( "click", function() {
$('.content').css( "background-position-x", "-1500px" );
});


Why doesn't the
.on
function work?

HTML Structure:

<div class="content">
<div class="play_button"><i class="fa fa-play-circle-o"></i></div>
</div>


Also I tried to make it work with
if
function, but it doesn't work either.

$('.play_button').on("click", "i", function() {

if ( $( '.play_button i' ).hasClass( ".first_section") ) {
$('.content').css( "background-position-x", "-1500px" );}
else {
$('.content').css( "background-position-x", "-800px" );
$(this).addClass('first_section');
}
});

Answer

I think you can rewrite your code so you just check the class inside same function:

$('.play_button i').click(function(){

    if ( !$(this).hasClass('first_section') ) {
        $('.content').css( "background-position-x", "-800px" );
        $(this).addClass('first_section');
    } else {
        $('.content').css( "background-position-x", "-1500px" );
    }

});

Your first snippet doesn't work because when you try to attach event handler $( '.play_button i.first_section' ).on( "click", function(){..}) the element with class first_section is not in the DOM yet so nothing is attached.

Your second snippet will work if you correct hasClass( ".first_section") to hasClass( "first_section") - no dot required.

In general the best way to append events to elements that are not currently in DOM is to use $("container").on("click","element",function() { ... }); where element is a jQuery selector for elements you want to bind to; and container is the element (e.g. div) that will hold newly created elements and already exists on page when you call this on method. Or just use $(document) if you have no any special container.

Comments