Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline JavaScript in `href` not working as expected in Firefox

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?

like image 924
Aidan Stanger Avatar asked Nov 18 '15 14:11

Aidan Stanger


2 Answers

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';">
like image 148
AtheistP3ace Avatar answered Oct 18 '22 03:10

AtheistP3ace


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.

like image 44
Alex K. Avatar answered Oct 18 '22 03:10

Alex K.