0

I have one function that refreshes the div but the then the jquery function won't work any more. I've seen answers where I have to use the about it losing the bindings but I can't get it to work.

refresh div code working fine

 $(document).on('click', '#reload', function () {
    //Load next question
    $("#new_sen").load(" #new_sen");   
});

My code that won't work after div refresh

 $(".card_flip").on('click', function() {
    $(this).toggleClass('flipped');

 })

Thanks for any help.

JohnnyQ
  • 484
  • 10
  • 23
  • 1
    maybe it's because you have an empty space in the load method: `load(" #...")` see how there's an empty space after the double quote after load. should be `load("#...")` – Abdul Ahmad Aug 25 '19 at 16:00
  • See "Delegated event handlers" in https://api.jquery.com/on/ You are destroying the event handler when you load new content. Either recreate the handler or use the example(s) in the link – Lee Taylor Aug 25 '19 at 16:02

2 Answers2

2

Does it throw an error or just not run? Try replacing:

$(".card_flip").on('click', function() {
    $(this).toggleClass('flipped');
})

with:

$(document).on('click', '.card_flip', function () 
    $('.card_flip').toggleClass('flipped');
})

If problem is a dynamic element not being handled, the former only applies to elements on the page when it's run. Latter should continue to handle any clicks for .card_flip elements added after page load.

Gavin
  • 2,214
  • 2
  • 18
  • 26
0

I think jQuery still works, it just loses the reference to the element if you use reload().

Try using html() on a container to load new questions:

 $("#new_sen").html('<div class="new_question">another question...</div>');
Anton Bks
  • 482
  • 3
  • 10