0

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');
    }
});
Community
  • 1
  • 1
SoSnA5115
  • 23
  • 3

1 Answers1

0

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.

Nikolay Ermakov
  • 5,031
  • 2
  • 11
  • 18
  • It's works, thank you! But I will Grateful if someone can explain why .on function don't work? – SoSnA5115 Jan 31 '16 at 00:25
  • Ok so what should I do if I want to reload DOM, it is possible? For example i add class to element, and in next snippet I want to make click function on it with this new class added, how it should work? – SoSnA5115 Jan 31 '16 at 00:41
  • You can attach an event handler right after adding a class to an element but in your case that wouldn't work because you will be attaching a new `click` handler every time the `i` is clicked ending up with growing number of handlers. For general approach see the update to my answer. Also check out - http://api.jquery.com/on/ – Nikolay Ermakov Jan 31 '16 at 01:20