Anton Styopin
Anton Styopin

Reputation: 753

JQuery get id after loaded html

I have a problem. I have two .html files.

<!DOCTYPE html>
<html><head>...</head>
<body>
    <ul><li id="home"><a>Home</a></li></ul>
    <div class="content"></div>
    <script type="text/javascript" src="Javascripts/navigation.js"></script>
</body>
</html>

and

<h1>Welcome!</h1>
<div id="imgPanel" style="background:red;">
    <img src="Images/me.png" class="img-responsive img-rounded"> 
</div>
<div id="textPanel" style="background:blue;"></div>

In my navigation.js I load the second .html file into the "content"-div of the first .html:

$(document).ready(function () {
    var content = $(".content");
    var a = $("#home");

    home();
    $('#textPanel').height( $('#imgPanel').height() );

    function home() {
        content.load("home.html");
    }

    a.on("click", function () {
        home();
    });
});

The loading works! My question is now:
How can I get the id of the div's of the second .html I loaded into the first one?
The var = $("#textPanel"); is null.

Upvotes: 3

Views: 2803

Answers (1)

Arg0n
Arg0n

Reputation: 8423

Since the content gets loaded asynchronously, you might want to change your code like this, to execute $('#textPanel').height() when it is available:

function home(){
    content.load("home.html", function(){
        $('#textPanel').height( $('#imgPanel').height() );
    });
}

From this specification of callbacks

EDIT

Alternative:

HTML of loaded content

<h1>Welcome!</h1>
<div id="imgPanel" style="background:red;">
    <img src="Images/me.png" class="img-responsive img-rounded" onload="setHeight()"> 
</div>
<div id="textPanel" style="background:blue;"></div>

JavaScript

$(document).ready(function () {
    var content = $(".content");
    var a = $("#home");

    home();

    function home() {
        content.load("home.html");
    }

    a.on("click", function () {
        home();
    });
});

function setHeight(){
    $('#textPanel').height($('#imgPanel').height());
}

Upvotes: 3

Related Questions