0

I have an anchor that's when click shows the content depending on what the id it matches. but the script doesn't work.

HTML:

<a href="javascript:ReverseDisplay('asd')">
Click to show/hide</a>

<div id="asd" style="display:none;">
<p>Content goes here.</p>
</div>

SCRIPT:

function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
else { document.getElementById(d).style.display = "none"; }
}

FIDDLE HERE

MIke
  • 619
  • 6
  • 29
  • 2
    Check [updated fiddle](http://jsfiddle.net/tusharj/qnxtdgum/2/), See http://stackoverflow.com/questions/32925912/why-class-selector-is-not-created-on-click-action/32925927#32925927 and http://stackoverflow.com/questions/31848850/code-in-the-jsfiddle-is-not-working/31848917#31848917 for reference of how fiddle options works – Tushar Oct 16 '15 at 03:35
  • if I'm looking for a jquery solution would I still not include the jquery tag? – MIke Oct 16 '15 at 03:36
  • The problem here is not of JS code, it's how fiddle works, check my second comment – Tushar Oct 16 '15 at 03:36
  • If you want jQuery solution See http://jsfiddle.net/tusharj/d3pj4zft/ – Tushar Oct 16 '15 at 03:38
  • your code looks fine... as Tushar said your fiddle has some issues with the setup... – Arun P Johny Oct 16 '15 at 03:39

2 Answers2

1

Your problem is this:

In the "Frameworks & Extensions" section, in the left sidebar of JSFiddle, you have the option "onLoad" selected. This causes your functions to be wrapped within an event listener (a function that runs only when the contents of the page has been loaded). Since your functions end up declared inside this event listener, they aren't available within the window object (the javascript's "global object"). So, when the click on the link tries to call the function, it will be "undefined" in the window object throwing an error (you can see this in the console of your browser). Just change that option to "No wrap - in head" and you will be fine. =)

In addiction, I would recommend you to name your functions with a lowered cased first letter, since it's a best practice to only start function names with a capital letter if the function is a constructor.

Matheus Dal'Pizzol
  • 5,735
  • 3
  • 19
  • 29
1

Remove onload from jsfiddle framework and extension check

Demo

Kishan
  • 1,182
  • 12
  • 26