Jen Jen - 5 months ago 11
jQuery Question

Loading an external html file that contains script to another div

This is my main index code. I want to insert an external html code within the div called "divPage."

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico" />
<title>Retail Exchange Network</title>
<meta name="viewport" content="width=device-width, initial-scale = 1, maximum-scale=1, user-scalable=no" />

<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Space+Mono" rel="stylesheet">

<!-- Personal Stylesheets -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="CSS/RXN/style.css">


<!-- Scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="JS/RXN/script.js"></script>

</head>

<body>

//header, navigation code here//

<!-- content -->
<div id="wrapper">
<div id="index-content">
<div id="divPage">

</div>
</div>
</div>

//footer code here//
</body>
</html>


This is the external html. When the user clicks on the thumbnails of the browser images, it should show and hide the information about that browser

<div data-scripturl="./GUI/Home/index.js">
//html code for this external file//
</div>


This is the ./GUI/Home/index.js script (this is to toggle tables within the external html)

(function () {
var $tables = $("table");
var previous = null;

var $thumbnails = $(".img-fluid.w-100.img-thumbnail");

var hide = function () {
$tables.hide();
};

var initialize = function () {
hide();
};

var registerEvents = function () {
$thumbnails.on("click", function (e) {
e.preventDefault();

var image = $(e.currentTarget);
var anchor = image.parent();
var href = anchor.attr("href");

hide();

if (previous === href) {
previous = null;
}
else {
$(href).show();
previous = href;
}
});
};

registerEvents();
initialize();
})();


And this is my script to insert the external to the main index.

$(document).ready(function () {
$("#divPage").load("GUI/Home/index.html");
});


My problem is, I'm able to insert the content of the external html into my main index.html, but the script that goes with the external html does not work. I'm still new to jQuery, so any advice for me will be really helpful!

Answer

I don't see any code for loading the script.

I think you could try:

$(document).ready(function() {
    $("#divPage").load("GUI/Home/index.html", function() {
        $.getScript($("#divPage").children(':first').attr('data-scripturl'));
    );
});
Comments