Retro Code
Retro Code

Reputation: 145

onclick event does not work in an embedded html

I have loaded a html file text into a div element using XMLHttpRequest. What I am exactly trying to say is that I have a main html page which is filled with another html file. The problem is that the onclick events of the embedded html's tags do not work. It seems that although I have added my script into embedded html, the functions cannot be found and called! Therefore, the below error can be seen in console.

the function is not defined at HTMLParagraphElement.onclick

I checked the src of the attached script (in embedded html) and it was ok. I also tried to move my scripts to the main page, because I thought that embedded html would see the script of its parent html, though it didn't work out. I am sure that I did the same thing, but I cannot remember how exactly I did it in the past.

The embedded Html

<head>
    <title>Menue</title>
    <link href="../styles/menue.css" rel="stylesheet" />
    <script src="../scripts/menue.js"></script>

</head>

<div id="menueContainer">
    <h2 id="menueGameTitle">Monsters' Den</h2>
    <h4 id="menueDesignerTitle">Designed and developed by Retro-Code (Mr. Shahrokni)</h4>

    <p id="menueDescription" onclick="MyFunction()">
        ...
    </p>

</div>

* The main Html*

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Monsters' Den</title>
    <link href="styles/Index.css" rel="stylesheet" type="text/css" />
    <script src="scripts/Index.js"></script>
</head>
    <body id="mainBody" onload="initIndexPage()">

        <div id="mainContainer">

            <div id="centeredFrame">

            </div>

        </div>
    </body>
</html>

How I load the embedded html into the div

function getHtml(url) {

    var xmlHttpRequest = new XMLHttpRequest();

    // add a random param at the end of the url to avoid cached data. 
    url = url + "?p=" + Math.random;

    xmlHttpRequest.open("GET", url, false);
    xmlHttpRequest.send(null);

    var response = xmlHttpRequest.responseText;
    return response;

}

function loadMenueinFrame() {

    var html = getHtml("./htmls/menue.html");
    var centeredFrame = document.getElementById("centeredFrame");
    centeredFrame.innerHTML = html;
}

I expect to see the consequence of the onclick event, but as it is described above it does not work. Hope you guys give me a hint. Thank you.

Upvotes: 1

Views: 1221

Answers (1)

Bama
Bama

Reputation: 577

Load the script in your head tag Let mySelectedElement = document.getElementByID("mainContainer"); mySelectedElement.addEventListener("click", function getHtml(){ //your handler here })

This should work I believe

Upvotes: 1

Related Questions