Al bassam
Al bassam

Reputation: 225

JQuery is still firing after it is removed in DOM with ajax load

I'm using Laravel 5.2 to develop my single page application. I have add.blade.php and has script in it and edit.blade.php with the same script, same class name and id. When I .load add.blade.php the script works fine. then dynamically .load the edit.blade.php, in this time the add.blade.php is removed in the DOM and its script. But its script is still firing not the one in my edit.blade.php.

BTW, My events are delegated. Thank you.

Upvotes: 0

Views: 78

Answers (1)

adosan
adosan

Reputation: 176

I think you expect the jQuery code to lose it's effect after you remove/replace the wrapping <script> tag. But it does not work this way.

Consider following example:

#script-wrapper{padding-left: 15px; border: solid 1px black; background-color: gold}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div id="script-wrapper">
  <h3> Script wrapper</h3>
  <p>foo() is defined in here</p>
  <script type="text/javascript">
    function foo() {
      alert("Foo");
    }
  </script>
</div>

<hr />

<input type="button" id="runFoo" value="Run foo()" />
<input type="button" id="removeScript" value="Remove script wrapper" />

<script type="text/javascript">
  jQuery("#runFoo").click(function () {
    foo();
  });

  jQuery("#removeScript").click(function () {
    jQuery("#script-wrapper").remove();
  });
</script>

In the above example we have function foo() defined within the #script-wrapper element. You can run this function with a button or remove the #script-wrapper with another one. Here you can notice, that the function can be fired even if the #script-wrapper is removed from the DOM.

If you wish to end up with current the function, you can "undefine" it manually. Removal of the #script-wrapper from the example wont do the "undefinition" for you.

foo = void(0); //this will set foo to undefined

Upvotes: 1

Related Questions