9

Why doesn't this inline javascript work in Firefox? And how can I get it to work correctly in Firefox?

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <style>
        h2 {display:inline; padding:0px 7px 0px;}
        h2 a {text-decoration:none}
        h2 a:link {color:#FFFFFF;} 
        h2#s0 {background-color:black;}
    </style>
</head>
<body>
    <h2 id="s0"><a href="javascript:document.getElementById('d0').style.display='block';">
Click me!</a></h2> 
    <div id="d0"
style="width:98%;border: 5px solid #000000;padding:3px; display:none;">
When you click the heading, this text should appear with a black
outline, with no gap between that and the heading background.</div>
</body>
</html>

In Safari this appears as it should. In Firefox it momentarily appears with a gap (as if the browser's in quirks mode) then everything on the page vanishes, replaced by the word "block". At first I thought that meant Firefox was blocking it, but it says "inline" instead if that's what I set the style to display.

EDIT: The Javascript part of my problem is now solved. But there's still a difference in the way the heading background appears: it extends down to the div border in Safari, but not in Firefox. Is there a way to make it do so in Firefox?

Aidan Stanger
  • 127
  • 1
  • 6

3 Answers3

11

The closest working form of what you have is:

<a href="javascript:void(document.getElementById('d0').style.display='block');">

Because:

When a browser follows a javascript: URI, it evaluates the code in the URI and then replaces the contents of the page with the returned value, unless the returned value is undefined. The void operator can be used to return undefined.

onclick is the better option here.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
3

On OSX firefox version 41.0.1 I also experienced the same issue in fiddle. I do not know why it does not work, it could be a bug in FireFox but you can do this to have a somewhat similar working solution:

<a href="#" onclick="document.getElementById('d0').style.display='block';">
AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43
3

Replace your link with this:

<a href="javaScript: void(0);" onclick="javascript:document.getElementById('d0').style.display='block';">

As far as i understand it, Firefox tries to open a URL if you put the javaScript call into the href attribute. (as you can see in your location bar) Putting it in the onclick instead makes it work fine.

I guess you could also use some preventDefault or such, and you could also try a href="#", but the a href="javaScript: void(0);" works just fine and is robust through all browsers i have tested so far.

Burki
  • 1,188
  • 19
  • 28