• Sign in to Neowin Faster!

    Create an account on Neowin to contribute and support the site.

  • 0
Sign in to follow this  

Some JavaScript help please!

Question

iamhiddensomewhere    0

I must be doing something wrong, because this doesn't work!

<html>

<head>

<style type="text/css">

#hidden { display: none; }

</style>

<script type="text/javascript">

var x=document.getElementById("hidden");

function show() {

x.style.display="block";

}

</script>

</head>

<body>

<a href="#" onclick="show()">show the next line!</a><br>

<p id="hidden">i am revealed!</p>

</body>

</html>

Anybody that knows JavaScript will know what I'm trying to do! Is there a way to assign a variable and use it in such a fashion? Am I just doing it wrong? Or...is there another way to do that? Thanks!

Share this post


Link to post
Share on other sites

1 answer to this question

Recommended Posts

  • 0
sharpenyourteeth    0

you are doing something wrong indeed ;)

you're trying to get the element before it's even loaded, so x has the value null

since you have your javascript in the head section, it is loaded before the <body> section, so when you say var x = document.getelementbyid("hidden"), that element doesn't actually exist yet because the browser hasnt got to the <body> tag to read the html. so to fix it all you have to do is put that statement inside the function.

you can actually do it in one line:

function show() {

document.getElementById("hidden").style.display="block"

}

hope that helps

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.