views:

29

answers:

4

I have a div block

<div id='block'> <a href="#" onclick="Document.getElementById('block').style = 'display: none;';">Hide</a> </div>

and I want to be have a link that will hide the block when clicked, I tried the above but it doesn't work I'm not sure how to get this to work, any ideas or guidance?

+3  A: 
<div id='block'>  <a href="#" onclick="Document.getElementById('block').style.display = 'none';">Hide</a>  </div>
Mike Sherov
+5  A: 

style is an object which properties are assigned directly. It's not like the HTML attribute. So what you want is:

document.getElementById('block').style.display = 'none';
Jason McCreary
Thank you for the explanation.
AFK
One question, will this not work if there are more elements within the div that aren't set to display = none? like a form or an image?
AFK
No problem. Other CSS properties can be assigned as well. Just keep in mind that JS uses camel case where CSS uses dashes. For example, CSS `background-color` in JS `element.style.backgroundColor`
Jason McCreary
Anything within that `div` will not be displayed, but only the div will have the `style.display = 'none'`.
Jason McCreary
@Jason McCreary is right, the child elements will inherit the display none from thier parent.
John
A: 

...or with some help from jquery:

$('#block').hide();
// or:
$('#block').css('display','none');
Tahbaza
A: 

It is better to put the javascript in the <head> or better yet a separate file not the HTML. But since you have it in the HTML you could shorten your code to onclick="this.parentNode.style.display='none';"

qw3n
Why, wouldn't the load times be increased if the webserver had to fetch yet another document?
AFK
Maybe, you have an extra HTTP request, but the code will be about the same size so it isn't that big of a deal. If this is the only piece of javascript on your page its not really that important. However, the more code you have the harder it is to debug and if you want to change something it can be a real pain. I know this from personal experience. :P
qw3n
you're right. I will probably do this to make it easier to code and just make an optimized version for speed later.
AFK