0

The script won't load after the ajax has loaded the html content, why is this simply step not working. Here is what I got:

MakoStart.html: (The main page that will change)

<div class="makoislandintro" id="makochange">   
    <div class="makochoicesfirst">
        <img src="../img/makoislandspecial/makobeach.jpg" class="makoislandbeach" id="makoislandbeach" alt="current">
        <br>
    </div>
</div>
<script>
    document.getElementById("makoislandbeach").onclick = function() {
       $('#makochange').load('makoisland.html');
    };  
</script>

This works, when i click the image with the id: makoislandbeach, the content changes to whats in makoisland.html.

Here is what is in makoisland.html:

<div class="makochoices">
    <div id="rightside">            
        <img src="../img/makoislandspecial/waterstream.jpg" class="makoislandchoice" id="waterstream" alt="right choice">
    </div>
    <div id="leftside">
        <img src="../img/makoislandspecial/islandside.jpg" class="makoislandchoice" id="islandside" alt="left choice">
    </div>
</div>
<script>
    document.getElementById("waterstream").onclick = function() {
       $('#makochange').load('waterstream.html');
    };
    document.getElementById("islandside").onclick = function() {
       $('#makochange').load('islandside.html');
    };  
</script>

Once the content changed, the script doesn't execute when i click the 2 new images that have replaced the old content. I have made a waterstream.html, it is the same as makoisland.html but with different images, but the script won't work after the first transition.

  • i suppose that the script in your makoisland.html can't access the dom element, which is located in the makostart.html – errand Jun 22 '17 at 13:44

1 Answers1

0

Take a look at this answer. As it said:

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.

Maybe you could do something like this. Instead of using load, use ajax. It's slightly different.

<div class="makoislandintro" id="makochange">   
    <div class="makochoicesfirst">
        <img src="../img/makoislandspecial/makobeach.jpg" class="makoislandbeach" id="makoislandbeach" alt="current">
        <br>
    </div>
</div>
<script>
    document.getElementById("makoislandbeach").onclick = function() {
        $.ajax({
            url: "makoisland.html",
            context: document.body,
            success: function(responseText) {
                $("#makoislandbeach").html(responseText);
                $("#makoislandbeach").find("script").each(function(i) {
                    eval($(this).text());
                });
            }
        });
    };
</script>
vojislavdjukic
  • 428
  • 2
  • 8