TW_
TW_

Reputation: 175

Panel only showing on specific page

I need a working javascript code which shows a certain panel only on one specific page on my website and hides it on the rest. It's a forum-esque setup.

Here's what I got so far.

<script type="text/javascript">

function ShowPanel()
{
if(document.location.href == "http://www.exampleurl.com")
{document.getElementById("panel").style.display = "block";}
else
{document.getElementById("panel").style.display = "none";}
}

</script>

        <div id="panel" onload="ShowPanel">
            Example text.
        </div>

According to the example code I've looked up, all of this seems to be reasonable, but obviously there's an error somewhere. Nothing happens.

Thanks for checking!

Upvotes: 0

Views: 219

Answers (2)

Plynx
Plynx

Reputation: 11461

Check what the document.location.href really is on the page by typing it into your console (F12, usually). For instance, most browsers will add the trailing slash onto a server name even if there isn't one in the URL. The match has to be exact for your code to work as written.

Another options is to compare document.location.pathname, which will have everything after the server name. If you want to make a case insensitive compare, you can use document.location.pathname.toLowerCase().

Upvotes: 0

Grant Clements
Grant Clements

Reputation: 984

The problem is that the onload event cannot be used on a DIV element. onload can only be used on the document body or an external resource (iframe, image, scripts).

Your best bet is to place your JavaScript at the bottom of the page instead.

e.g.

<div id="panel">
    Example text.
</div>

<script language="JavaScript">
if(document.location.href == "http://www.exampleurl.com"){
    document.getElementById("panel").style.display = "block";
}
else {
    document.getElementById("panel").style.display = "none";
}    
</script>

Upvotes: 1

Related Questions