How to restore JQuery events on removed element?

Viewed 128

With this PHP I add the following HTML. I use PHP because I retrieve information from the database, but it's irrelevant in this question.

<?php
    echo "
    <div id='user_bio_container'>
    <p id='user_bio'>My bio<i id='user_bio_edit' class='fas fa-edit'></i></p>
    </div>
    ";
?>

This is the script I have. When the user clicks the bio paragraph, it stores the inside of the paragraph in a variable, then empties the container and adds a form. If the form is cancelled I want to remove the form and add the previous HTML I had in the paragraph. The problem is that when I try to do so the new paragraph does not respond to events (mouseover, click...).

    $('#user_bio_edit').css("display", "none");
    $(document).ready(function(){
        $("#user_bio").on('mouseover', function(){
            $('#user_bio_edit').css("display", "inline");
        });

        $("#user_bio").on('mouseleave', function(){
            $('#user_bio_edit').css("display", "none");
        });

        $("#user_bio").on('click', function(){
            var actualbio = $("#user_bio_container").html();
            $('#user_bio_container').empty();
            var user_bio_form = 
            "<form id='change_user_bio'>" +
            "<span id='cancel_user_bio'>Cancel</span>"
            "</form>";
            $("#user_bio_container").append(user_bio_form);

        //Button decision control
        $("#cancel_user_bio").on('click', function(){
            $("#user_bio_container").empty();
            $("#user_bio_container").append(actualbio);
            $('#user_bio_edit').css("display", "none");
        });

        });

    });

I have tried using hide() and show(), but after two cancelled forms it stops working and I keep adding forms to the HTML that are not shown. I also tried moving the button decision control code outside the click event, but it does not work either.

1 Answers

This is a scope issue. actualbio is not available outside $("#user_bio").on('click', function(){..}

Change this

var actualbio = $("#user_bio_container").html();

to

actualbio = $("#user_bio_container").html();

and use

var actualbio = ''; 

just below

$(document).ready(function(){

this way the variable actualbio is available in all events handlers inside $(document).ready

Regarding the events not working issue

You need to attach events like this since #user_bio is removed from dom along with all attached events when you cleared the html.

$("#user_bio_container").on('mouseover', "#user_bio", function() {......})
Related