boomslang
boomslang

Reputation: 118

JQuery : Removing DOM objects that have been added in load()

File contents are given below. I have a button, "load_button", whose click event triggers a load() function. The html file loaded with the function contains another button, "my_button". The callback of the load() function adds a handler for the click event of "my_button". The problem is, every time I press "load_button", a new click event handler is added, and the alert in the event handler pops up multiple times. I want to delete previously created "my_button" with its event handler, before creating the new one. What I tried is adding the following command, where its commented out in the file descriptions below.

$('#page').empty(); 

No luck. I wanted a general solution, since I'll have other DOM objects to be removed. How can I remove them?

Also, it does not work when I replace

$('#page').on('click', '#my_button', function () {

with

$("#my_button").click(function()    {

Why isn't it working? Isn't the callback function of load() supposed to be run after the loading is done, and DOM objects are available?

main.html

<html>
    <head>
        ...
        <script src="main.js"></script>
    </head>
    <body>
        ...
        <a id="load_button">Load!</a>
        <div id="page">
        </div>
    </body>
</html>

1.html

<div>
    <a id="my_button">Go!</a>
</div>

main.js

$(document).ready(function(){

    $('#load_button').click(function()    {
//      $('#page').empty();
        $("#page").load('1.html', load_scripts());

    });
});

function load_scripts() {
    $.getScript('script.js');
}

script.js

$(document).ready(function(){

     $('#page').on('click', '#my_button', function () {
//   $("#my_button").click(function()    {
        alert('COWABUNGA!');
    });

});

Upvotes: 2

Views: 897

Answers (1)

bfavaretto
bfavaretto

Reputation: 71918

It looks like you don't need to load scripts dynamically at all. Try a main.js that looks like this:

$(document).ready(function(){

    $('#load_button').click(function()    {
        $("#page").load('1.html');
    });

    $('#page').on('click', '#my_button', function () {
        alert('COWABUNGA!');
    });

});

Upvotes: 2

Related Questions