The built-in JavaScript in `href` does not work in Firefox

Why does this embedded javascript not work in Firefox? And how can I make it 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, it looks as it should. In Firefox, it appears for a moment with a space (like a browser in quirks mode), then everything on the page disappears, is replaced by the word "block". At first, I thought it meant that Firefox was blocking it, but instead it says "inline" if that is what I asked to display the style.

EDIT: Now the Javascript part of my problem is resolved. But there is still a difference in how the background title looks: it extends to the Div border in Safari, but not in Firefox. Is there a way to do this in Firefox?

+8
javascript html css firefox
source share
3 answers

The closest working form of what you have:

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

Because :

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

onclick is the best option here.

+7
source share

Replace the link as follows:

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

As far as I understand, Firefox is trying to open the url if you put a javaScript call in the href attribute. (as you can see in your location) Putting it onclick , instead, it works fine.

I think you can also use some preventDefault or some, and you can also try a href="#" , but a href="javaScript: void(0);" It works just fine and works reliably in all browsers that I have tested so far.

+3
source share

On OSX firefox version 41.0.1, I also ran into the same problem in the fiddle. I don’t know why this does not work, it may 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';"> 
+1
source share

All Articles