...">

Javascript: style.display: "block" does not work

any idea why this javascript just shows a “block” and not the contents of a (hidden) DIV?

<html> <body> <div id="mydiv" style="display:none">TEST</div> <a href="javascript:document.getElementById('mydiv').style.display='block';">Show my DIV</a> </body> </html> 

I also tried inline, but with the same result.

return false / true also failed.

onclick = '' also failed.

I know there is a style. visibility, etc., but I don’t need / block.

Also, the function should work inside the link, I do not want to call an external JS function.

Thanks!

+2
javascript css
source share
3 answers

Since you want to use the onclick event handler rather than the href attribute:

 <a href="#" onclick="document.getElementById('mydiv').style.display='block';">Show my DIV</a> 

JsFiddle example

(side of note: inline JavaScript is usually not approved)

+5
source share

Javascript expression value

 document.getElementById('mydiv').style.display='block' 

- string 'block' - think about how you can do a=b='something' - in javascript the value of the assignment expression is the assigned value.

If you try

 <a href="javascript:'howdy'">link</a> 

You will see that clicking on the link moves to a document containing only the word howdy - and the same thing happens with your code. You can stop this by adding an explicit void(0) , or by wrapping the code in a function expression with an instant call that does not return a value (i.e. implicitly returns undefined ), therefore:

 <a href="javascript:(function(){document.getElementById('mydiv').style.display='block';})()"> 

(This structure is commonly used in bookmarklets). However, as noted in a few comments, the overall use of javascript: hrefs is disapproving, and you should consider using event handling.

+3
source share

This code describes your problem: http://jsbin.com/jigiy/1

 <div id="mydiv" style="display:none">TEST</div> <a href="javascript:document.getElementById('mydiv').style.display='block',false;">Show my DIV</a> 

Why is this happening:

Javascript seters return an input value, so document.getElementById('mydiv').style.display='block' will return 'block' , which is equal to href="javascript:'block'" . Now it refers to about:blank and sets its contents to block .

I'm not sure why browsers link and set the contents of about:blank , but I think this has something to do with the data URLs.

0
source share

All Articles