JS script execution at content loaded via AJAXHow can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?How to manage a redirect request after a jQuery Ajax callAbort Ajax requests using jQueryHow can I know which radio button is selected via jQuery?How do I attach events to dynamic HTML elements with jQuery?jQuery AJAX submit formHow to make an AJAX call without jQuery?ajax loaded content, script is not executingIs Safari on iOS 6 caching $.ajax results?Script to be executed in a Div loaded by Ajax

Noob at soldering, can anyone explain why my circuit wont work?

Thesis' "Future Work" section – is it acceptable to omit personal involvement in a mentioned project?

Why do unstable nuclei form?

How to slow yourself down (for playing nice with others)

Pre-1993 comic in which Wolverine's claws were turned to rubber?

Improving Sati-Sampajañña (situative wisdom)

Why do the Avengers care about returning these items in Endgame?

Are there variations of the regular runtimes of the Big-O-Notation?

What was the plan for an abort of the Enola Gay's mission to drop the atomic bomb?

Can the president of the United States be guilty of insider trading?

What does this quote in Small Gods refer to?

Windows OS quantum vs. SQL OS Quantum

What food production methods would allow a metropolis like New York to become self sufficient

Was the Highlands Ranch shooting the 115th mass shooting in the US in 2019

A Cunning Riley Riddle

No such column 'DeveloperName' on entity 'RecordType' after Summer '19 release on sandbox

Question about tidal forces and the Roche limit

Is every story set in the future "science fiction"?

What does formal training in a field mean?

Why did they go to Dragonstone?

Exception propagation: When to catch exceptions?

Which other programming languages apart from Python and predecessor are out there using indentation to define code blocks?

Why use steam instead of just hot air?

My perfect evil overlord plan... or is it?



JS script execution at content loaded via AJAX


How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?How to manage a redirect request after a jQuery Ajax callAbort Ajax requests using jQueryHow can I know which radio button is selected via jQuery?How do I attach events to dynamic HTML elements with jQuery?jQuery AJAX submit formHow to make an AJAX call without jQuery?ajax loaded content, script is not executingIs Safari on iOS 6 caching $.ajax results?Script to be executed in a Div loaded by Ajax






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have some simple code like this:



JS:



function load (element, url) 
element.innerHTML = '';
fetch(url).then(function (resp)
return resp.text();
).then(function (content)
element.insertAdjacentHTML('afterbegin', content);
);



Content of url parameter of load function:



<div>
<button id="some-button">Execute click!</button>
</div>

<script>
document.addEventListener('DOMContentLoaded', function ()
document.getElementById('some-button').addEventListener('click', function ()
alert('Click at button has been executed.');
);
);
</script>


My question is: Why click event (or any other JS code) does not work? HTML content is loaded, script tag also do, but JS code does not executing. I just want to replace jQuery function load with custom function load described above.



Thanks in advance!










share|improve this question
























  • Because you create a new button, which has not an event listener attached. DOMContentLoaded isn't triggered by the AJAX call.

    – Teemu
    Mar 23 at 10:02











  • Listening for DOMContentLoaded event in main page that occurred before the ajax was even made. Will not work the same as jQuery ready does if page is already loaded

    – charlietfl
    Mar 23 at 10:02












  • @Teemy But if I remove DOMContentLoaded event, code will still not work, although click event is attached to the button.

    – Hello Py
    Mar 23 at 10:54

















0















I have some simple code like this:



JS:



function load (element, url) 
element.innerHTML = '';
fetch(url).then(function (resp)
return resp.text();
).then(function (content)
element.insertAdjacentHTML('afterbegin', content);
);



Content of url parameter of load function:



<div>
<button id="some-button">Execute click!</button>
</div>

<script>
document.addEventListener('DOMContentLoaded', function ()
document.getElementById('some-button').addEventListener('click', function ()
alert('Click at button has been executed.');
);
);
</script>


My question is: Why click event (or any other JS code) does not work? HTML content is loaded, script tag also do, but JS code does not executing. I just want to replace jQuery function load with custom function load described above.



Thanks in advance!










share|improve this question
























  • Because you create a new button, which has not an event listener attached. DOMContentLoaded isn't triggered by the AJAX call.

    – Teemu
    Mar 23 at 10:02











  • Listening for DOMContentLoaded event in main page that occurred before the ajax was even made. Will not work the same as jQuery ready does if page is already loaded

    – charlietfl
    Mar 23 at 10:02












  • @Teemy But if I remove DOMContentLoaded event, code will still not work, although click event is attached to the button.

    – Hello Py
    Mar 23 at 10:54













0












0








0








I have some simple code like this:



JS:



function load (element, url) 
element.innerHTML = '';
fetch(url).then(function (resp)
return resp.text();
).then(function (content)
element.insertAdjacentHTML('afterbegin', content);
);



Content of url parameter of load function:



<div>
<button id="some-button">Execute click!</button>
</div>

<script>
document.addEventListener('DOMContentLoaded', function ()
document.getElementById('some-button').addEventListener('click', function ()
alert('Click at button has been executed.');
);
);
</script>


My question is: Why click event (or any other JS code) does not work? HTML content is loaded, script tag also do, but JS code does not executing. I just want to replace jQuery function load with custom function load described above.



Thanks in advance!










share|improve this question
















I have some simple code like this:



JS:



function load (element, url) 
element.innerHTML = '';
fetch(url).then(function (resp)
return resp.text();
).then(function (content)
element.insertAdjacentHTML('afterbegin', content);
);



Content of url parameter of load function:



<div>
<button id="some-button">Execute click!</button>
</div>

<script>
document.addEventListener('DOMContentLoaded', function ()
document.getElementById('some-button').addEventListener('click', function ()
alert('Click at button has been executed.');
);
);
</script>


My question is: Why click event (or any other JS code) does not work? HTML content is loaded, script tag also do, but JS code does not executing. I just want to replace jQuery function load with custom function load described above.



Thanks in advance!







javascript ajax






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 9:58









Mark Meyer

43k33766




43k33766










asked Mar 23 at 9:57









Hello PyHello Py

31




31












  • Because you create a new button, which has not an event listener attached. DOMContentLoaded isn't triggered by the AJAX call.

    – Teemu
    Mar 23 at 10:02











  • Listening for DOMContentLoaded event in main page that occurred before the ajax was even made. Will not work the same as jQuery ready does if page is already loaded

    – charlietfl
    Mar 23 at 10:02












  • @Teemy But if I remove DOMContentLoaded event, code will still not work, although click event is attached to the button.

    – Hello Py
    Mar 23 at 10:54

















  • Because you create a new button, which has not an event listener attached. DOMContentLoaded isn't triggered by the AJAX call.

    – Teemu
    Mar 23 at 10:02











  • Listening for DOMContentLoaded event in main page that occurred before the ajax was even made. Will not work the same as jQuery ready does if page is already loaded

    – charlietfl
    Mar 23 at 10:02












  • @Teemy But if I remove DOMContentLoaded event, code will still not work, although click event is attached to the button.

    – Hello Py
    Mar 23 at 10:54
















Because you create a new button, which has not an event listener attached. DOMContentLoaded isn't triggered by the AJAX call.

– Teemu
Mar 23 at 10:02





Because you create a new button, which has not an event listener attached. DOMContentLoaded isn't triggered by the AJAX call.

– Teemu
Mar 23 at 10:02













Listening for DOMContentLoaded event in main page that occurred before the ajax was even made. Will not work the same as jQuery ready does if page is already loaded

– charlietfl
Mar 23 at 10:02






Listening for DOMContentLoaded event in main page that occurred before the ajax was even made. Will not work the same as jQuery ready does if page is already loaded

– charlietfl
Mar 23 at 10:02














@Teemy But if I remove DOMContentLoaded event, code will still not work, although click event is attached to the button.

– Hello Py
Mar 23 at 10:54





@Teemy But if I remove DOMContentLoaded event, code will still not work, although click event is attached to the button.

– Hello Py
Mar 23 at 10:54












2 Answers
2






active

oldest

votes


















0














I think JS code included like that does not get recognized as JS code. I mean, text containing <script> tag is not considered as JS code and not run. Tried the following and it seems to work. Not sure if this solves your requirement, but it might help you understand the issue. Note the usage of document.createElement('script')






<div id="content"></div>
<script>
var scr = `document.getElementById('some-button').addEventListener('click', function ()
alert('Click at button has been executed.');
);`;
var content = `<div><button id="some-button">Execute click!</button></div>`;

document.getElementById('content').insertAdjacentHTML('afterbegin', content);
var sel = document.createElement('script');
sel.text = scr;
document.getElementById('content').appendChild(sel);
</script>








share|improve this answer






























    0














    Here is final working code:



    fetch(url).then(function (resp) 
    return resp.text();
    ).then(function (body)
    element.insertAdjacentHTML('afterbegin', body);
    let scripts = element.getElementsByTagName('script');

    for (let scr of scripts)
    var scriptContent = scr.innerText;
    var newScript = document.createElement('script');
    newScript.text = scriptContent;
    scr.remove();
    element.appendChild(newScript);

    );





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55312544%2fjs-script-execution-at-content-loaded-via-ajax%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      I think JS code included like that does not get recognized as JS code. I mean, text containing <script> tag is not considered as JS code and not run. Tried the following and it seems to work. Not sure if this solves your requirement, but it might help you understand the issue. Note the usage of document.createElement('script')






      <div id="content"></div>
      <script>
      var scr = `document.getElementById('some-button').addEventListener('click', function ()
      alert('Click at button has been executed.');
      );`;
      var content = `<div><button id="some-button">Execute click!</button></div>`;

      document.getElementById('content').insertAdjacentHTML('afterbegin', content);
      var sel = document.createElement('script');
      sel.text = scr;
      document.getElementById('content').appendChild(sel);
      </script>








      share|improve this answer



























        0














        I think JS code included like that does not get recognized as JS code. I mean, text containing <script> tag is not considered as JS code and not run. Tried the following and it seems to work. Not sure if this solves your requirement, but it might help you understand the issue. Note the usage of document.createElement('script')






        <div id="content"></div>
        <script>
        var scr = `document.getElementById('some-button').addEventListener('click', function ()
        alert('Click at button has been executed.');
        );`;
        var content = `<div><button id="some-button">Execute click!</button></div>`;

        document.getElementById('content').insertAdjacentHTML('afterbegin', content);
        var sel = document.createElement('script');
        sel.text = scr;
        document.getElementById('content').appendChild(sel);
        </script>








        share|improve this answer

























          0












          0








          0







          I think JS code included like that does not get recognized as JS code. I mean, text containing <script> tag is not considered as JS code and not run. Tried the following and it seems to work. Not sure if this solves your requirement, but it might help you understand the issue. Note the usage of document.createElement('script')






          <div id="content"></div>
          <script>
          var scr = `document.getElementById('some-button').addEventListener('click', function ()
          alert('Click at button has been executed.');
          );`;
          var content = `<div><button id="some-button">Execute click!</button></div>`;

          document.getElementById('content').insertAdjacentHTML('afterbegin', content);
          var sel = document.createElement('script');
          sel.text = scr;
          document.getElementById('content').appendChild(sel);
          </script>








          share|improve this answer













          I think JS code included like that does not get recognized as JS code. I mean, text containing <script> tag is not considered as JS code and not run. Tried the following and it seems to work. Not sure if this solves your requirement, but it might help you understand the issue. Note the usage of document.createElement('script')






          <div id="content"></div>
          <script>
          var scr = `document.getElementById('some-button').addEventListener('click', function ()
          alert('Click at button has been executed.');
          );`;
          var content = `<div><button id="some-button">Execute click!</button></div>`;

          document.getElementById('content').insertAdjacentHTML('afterbegin', content);
          var sel = document.createElement('script');
          sel.text = scr;
          document.getElementById('content').appendChild(sel);
          </script>








          <div id="content"></div>
          <script>
          var scr = `document.getElementById('some-button').addEventListener('click', function ()
          alert('Click at button has been executed.');
          );`;
          var content = `<div><button id="some-button">Execute click!</button></div>`;

          document.getElementById('content').insertAdjacentHTML('afterbegin', content);
          var sel = document.createElement('script');
          sel.text = scr;
          document.getElementById('content').appendChild(sel);
          </script>





          <div id="content"></div>
          <script>
          var scr = `document.getElementById('some-button').addEventListener('click', function ()
          alert('Click at button has been executed.');
          );`;
          var content = `<div><button id="some-button">Execute click!</button></div>`;

          document.getElementById('content').insertAdjacentHTML('afterbegin', content);
          var sel = document.createElement('script');
          sel.text = scr;
          document.getElementById('content').appendChild(sel);
          </script>






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 23 at 11:36









          Keerthi Kumar PKeerthi Kumar P

          1,113513




          1,113513























              0














              Here is final working code:



              fetch(url).then(function (resp) 
              return resp.text();
              ).then(function (body)
              element.insertAdjacentHTML('afterbegin', body);
              let scripts = element.getElementsByTagName('script');

              for (let scr of scripts)
              var scriptContent = scr.innerText;
              var newScript = document.createElement('script');
              newScript.text = scriptContent;
              scr.remove();
              element.appendChild(newScript);

              );





              share|improve this answer



























                0














                Here is final working code:



                fetch(url).then(function (resp) 
                return resp.text();
                ).then(function (body)
                element.insertAdjacentHTML('afterbegin', body);
                let scripts = element.getElementsByTagName('script');

                for (let scr of scripts)
                var scriptContent = scr.innerText;
                var newScript = document.createElement('script');
                newScript.text = scriptContent;
                scr.remove();
                element.appendChild(newScript);

                );





                share|improve this answer

























                  0












                  0








                  0







                  Here is final working code:



                  fetch(url).then(function (resp) 
                  return resp.text();
                  ).then(function (body)
                  element.insertAdjacentHTML('afterbegin', body);
                  let scripts = element.getElementsByTagName('script');

                  for (let scr of scripts)
                  var scriptContent = scr.innerText;
                  var newScript = document.createElement('script');
                  newScript.text = scriptContent;
                  scr.remove();
                  element.appendChild(newScript);

                  );





                  share|improve this answer













                  Here is final working code:



                  fetch(url).then(function (resp) 
                  return resp.text();
                  ).then(function (body)
                  element.insertAdjacentHTML('afterbegin', body);
                  let scripts = element.getElementsByTagName('script');

                  for (let scr of scripts)
                  var scriptContent = scr.innerText;
                  var newScript = document.createElement('script');
                  newScript.text = scriptContent;
                  scr.remove();
                  element.appendChild(newScript);

                  );






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 23 at 13:40









                  Hello PyHello Py

                  31




                  31



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55312544%2fjs-script-execution-at-content-loaded-via-ajax%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript