W
W
way_t2018-03-22 06:25:58
css
way_t, 2018-03-22 06:25:58

How to organize the work of a function that uses the added jQuery class?

Hello.

$('.podcast__play').on('click', function() {
       $(this).addClass('playing');
    })

    $('.playing').on('click', function() {
            console.log('test');
    })


Please tell me why the function is not processed when clicking on playing? So I understand, you need to track this event additionally. Any ideas how this can be implemented?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis, 2018-03-22
@way_t

$('body').on('click', '.playing', function() {
            console.log('test');
    });

W
wallydnb, 2018-03-22
@wallydnb

The event is not processed because it is hung on elements that have the playing class at the time the function is executed. Your class is applied later, on the click event.
Perhaps you wanted to do something like this:

function handleStoped() {
        console.log('stoped')
        $(this).removeClass('playing')
        $(this).text('play')
        $(this).off('click', handleStoped)
        $(this).on('click', handlePlaying)
}
function handlePlaying() {
        console.log('playing')
        $(this).addClass('playing')
        $(this).text('stop')
        $(this).off('click', handlePlaying)
        $(this).on('click', handleStoped)
}
$('.podcast__play').on('click', handlePlaying)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question