-1

Sorry to bother with this kind of questions, i tried to look out for a solution to my problem but couldn't find any that applied.

I'm trying to toggle a class on an element by clicking on another element, by doing this:

var myCanvas = document.querySelector('main');

function btOne() {
  myCanvas.classList.toggle("one");
}

I defined the div i wanted to add a class to and defined the function.

<main></main>
<div class="pickers">
  <div class="pick one" onclick="btOne()"></div>
</div>

It says the function is not defined when i click the div. I can't seem to figure out what's wrong with it. Check my DEMO to really see what's going on.

On a side note, I'm trying not to use libraries such as jQuery.

St Klauz
  • 65
  • 1
  • 9

1 Answers1

4

JSFiddle is wrapping your code in an onload callback which causes function btOne to be scoped within the function, and not implicitly globally scoped.

If you want to have btOne available in global scope, you need to explicitly assign it:

window.btOne = btOne;

updated fiddle

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • why on earth would you suggest that.. no code edits need be made whatsoever, just put the code at the bottom of body and it works. on the fiddle the exact code works if you change the load type to nowrap-body – I wrestled a bear once. Apr 18 '16 at 16:06
  • @Pamblam, it's better to be explicit in intent and portable, than rely on implicit behavior that suddenly breaks unexpectedly. – zzzzBov Apr 18 '16 at 16:34
  • @Pamblam, and there are many more issues with the code, using inline event handlers at all is a bad idea, but this question was about how to fix the issue of a missing global reference. – zzzzBov Apr 18 '16 at 16:35
  • right, i was wondering why you were providing best practices rather than easy fix answer, but not mentioning any of that in the question.. imo, if you're going to provide a best practice answer you should have explained all that in your answer. if youre going to give him a quick fix, this ain't it, lol.. sorry for bitching. +1. – I wrestled a bear once. Apr 18 '16 at 16:41
  • @Pamblam, shortly after I posted this answer the question was (correctly) closed as a duplicate, so I stopped my normal rewrite/polish cycle. I half expect this question to be deleted given that it's downvoted and closed. – zzzzBov Apr 18 '16 at 16:48