A
A
Alexander Kuznetsov2022-04-08 14:01:47
AJAX
Alexander Kuznetsov, 2022-04-08 14:01:47

Why doesn't Jquery toggle work after ajax?

Hello guys
There is such a jquery

The usual class toggle
In three variations

$(document).on('click', '#play', function() {
                    if ($(this).hasClass('fa-play')) {
                        $('#play').removeClass('fa-play');
                        $('#play').addClass('fa-pause');
                        audio.play();
                    } else if($(this).hasClass ('fa-pause')) {
                        $('#play').removeClass('fa-pause');
                        $('#play').addClass('fa-play');
                        audio.pause();
                    } else {

                    }
                });

$('#play1').click(function() {
                    if ($(this).hasClass('fa-play')) {
                        $('#play1').removeClass('fa-play').addClass('fa-pause');
                        audio1.play();
                    } else {
                        $('#play1').removeClass('fa-pause').addClass('fa-play');
                        audio1.pause();
                    }
                    $(this).addClass("fa-pause");  
                });

$("#play1").click(changeClass);
                function changeClass() {
                   $("#play1").toggleClass("fa-play fa-pause");
                   if ($(this).hasClass('fa-play')) {
                       audio1.pause();
                    } else {
                        audio1.play();
                    }
                };


Here is its html

<div class="controlvoice">
<i class="fa fa-play" id="play1"></i>
</div>


But when launching a popup window on ajax from this script:
https://github.com/dimsemenov/Magnific-Popup

Yes, and from others (tried several)
The class stops switching / adding.

What to do?
How to be?
Save!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Olga, 2022-04-08
@Liatano

3 handlers are hung on the button, and in the first case there is a delegation - the handler is hung on the page and it checks whether it is a button. In the case of Ajax, the button is probably recreated, which kills the second 2 handlers. It is necessary to make delegation everywhere, as in the first case.
Or I didn't understand the problem?

T
ThunderCat, 2022-04-08
@ThunderCat

1) replace the id with a class, since with IDs when creating and deleting elements you will have crap with duplicate IDs.
2) should work fine. 3) in the switching code, it is overwrought with ifs $(document).on('click', '.play', function() {...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question