Question

I am creating a JavaScript bookmarklet to toggle the visibility of an HTML Element on a page, but it seems like just hiding the element is troublesome:

http://codepen.io/anon/pen/HtkzL

Code:

<div id="hideme">
  <p>I am a div that needs to be hidden</p>
</div>

<p>I am a paragraph that doesn't need to be hid.</p>

<blockquote>
  I am a blockquote that the whole world must see
</blockquote>

<a href="javascript:var a=document.getElementById('hideme');a.style.display='none';">Click me to hide the div.</a>

what's happening is that every the anchor link is clicked, the entire page goes blank and says "none".

When I inject the exact same code in the <a> ... </a> in a JS console, it works just fine.

Any possible fixes for the problem?

Était-ce utile?

La solution

It actually is hiding the element, but it's also following your anchor right after (to nowhere). You can return false, or a falsy value. I'd wrap it in void which will return undefined, but either will work. Here's your codepen and the code: http://codepen.io/anon/pen/dsgKk

<a href="javascript:void(function(){ var a = document.getElementById('hideme'); a.style.display='none'; })();">Click me to hide the div.</a>

(This would also work, but is less clean, imo):

<a href="javascript:var a=document.getElementById('hideme'); a.style.display='none'; return false;">Click me to hide the div.</a>

Autres conseils

getElementById('hideme');a.style

Offhand, I'd say because the browser is confused with your variable name;

also, the code would be:

getElementById('hideme').style.display.....

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top