Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

innerHTML disappearing quickly from div in jQuery load file

innerHTML appears then quickly disappears in under a second, div in a jquery load file.

main.js

$(document).ready(function () {
    $('#page1').click(function () {
        $('#page-content-wrapper').load('page1.html');
        document.getElementById("changeme").innerHTML = "Paragraph changed!";
    })
});

index.html

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!DOCTYPE html>
<html>
<head>
    <script src="js/site.js"></script>
    <meta charset="utf-8" />
    <title>TimeApp</title>
</head>
<body>
    <a id="page1">Page 1</span></a> <a id="page2">Page 2</span></a>
    <div id="page-content-wrapper">
        <!-- Page content is loaded here -->
    </div>
</body>
</html>

page1.html

<div id="changeme"></div>

>Solution :

The issue is because load() makes an AJAX request to retrieve the content from page1.html. While this is happening you update the innerHTML of the element within the #page-content-wrapper. When the AJAX request completes, the content of page1.html overwrites the existing content – which you just updated.

To fix the problem put the line which updates the text of the element in the callback of load(), so that it’s only ever executed after the AJAX request:

jQuery($ => {
  $('#page1').click(function() {
    $('#page-content-wrapper').load('page1.html', () => {
      $("#changeme").text("Paragraph changed!");
    });
  });
});

Better still, put the content you need in to page1.html directly, to avoid this unnecessary code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading