Search code examples
javascriptsyntaxweblogic

Simple Javascript if statement problem


I'm sure the solution is glaringly obvious, but I've spent an hour faffing about so would really appreciate any help!

The following javascript is meant to make a div visiable and another div invisible if the variable loggedin="true":

/* Javascript */

function showArticle()
{
document.getElementById('full').style.display = 'block';
document.getElementById('summary').style.display = 'none';
}
var loggedin="true";
var owned="true";
if (loggedin="true")
{
document.write("Logged In");
}
if (owned="true")
{
    showArticle();
}

.

<!-- HTML -->
<div id="summary">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>

<div id="full" style="display:none;">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur.
<div>

Am I right in thinking the issue is with my calling of the showArticle function?


Solution

  • I copied your code into a text file and tried it - and it had the problem.

    I put the javascript in script tags above the html.

    <html>
    <body>
    
    <script>
    function showArticle()
    {
    document.getElementById('full').style.display = 'block';
    document.getElementById('summary').style.display = 'none';
    }
    var loggedin="true";
    var owned="true";
    if (loggedin="true")
    {
    document.write("Logged In");
    }
    if (owned="true")
    {
        showArticle();
    }
    
    </script>
    
    <!-- HTML -->
    <div id="summary">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>
    
    <div id="full" style="display:none;">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur.
    <div>
    
    
    </body>
    </html>
    

    This fails because when the javascript runs the div tags have not been added to the DOM, so the getElementById returns null. I found this by using debugging the javascript in Firebug / Firefox.

    If I moved the javascript to after the html, it works - as the DOM is then loaded with those items.

    <html>
    <body>
    <!-- HTML -->
    <div id="summary">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>
    
    <div id="full" style="display:none;">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur.
    <div>
    
    <script>
    function showArticle()
    {
    document.getElementById('full').style.display = 'block';
    document.getElementById('summary').style.display = 'none';
    }
    var loggedin="true";
    var owned="true";
    if (loggedin="true")
    {
    document.write("Logged In");
    }
    if (owned="true")
    {
        showArticle();
    }
    
    </script>
    </body>
    </html>