I was toying around with trying to get events-on-button-click to work where the JavaScript code triggers some event once a specific button is clicked.
There are no issues when I attempt to do on-click triggers in my project(s), but I just can't seem to get it to work using JSFiddle.
I first followed the tips here: JavaScript not running on jsfiddle.net
Specifically, the part where meder omuraliev writes, "So instead of
<p onclick="lol()" id="foo">
you'd do
var e = document.getElementById('foo');
e.onclick = lol;
in the JS only."
I attempted to follow this instruction which can be seen in the simple example I made here (that doesn't work): https://jsfiddle.net/b7yj3cph/3/
var e = document.getElementById('test');
e.onclick = example;
var example = function( {
alert("hello");
});
<button id='test' type="button" onclick="example()">
<div>
Hello
</div>
I tried other sources and methods but couldn't get any to work. I attempted an example from W3Schools (https://jsfiddle.net/b7yj3cph/) and tried some JSFiddles from searching "jsfiddle button onclick" (https://jsfiddle.net/Dogbyte/62cd0LLq/) which some didn't work.
But some did; like this one (http://jsfiddle.net/lesson8/h4JXs/1/) seems to work fine.
What is uniquely going on that makes the click trigger work for some JSFiddles and not for others? I suspect it has to do with the $(document).ready()
part but I've been reading various ways to get this to work and I can't find anything that makes sense to me.
Going back to the Stack Overflow thread that I shared earlier, the top-voted response there had 3 suggestions:
- "( easiest, quickest, not ideal ) - change function blah(){} to window.blah = function(){}; making the functions global."
Well, in the JSFiddle posted here that works as expected, there is no use of window
. Attempts that I made to use window
proved to be fruitless.
- "( ideal way ) - use unobtrusive Javascript to attach behaviour to DOM elements from within the JS solely, meaning separate HTML from JS."
This is a great point and makes sense but still didn't solve my particular issue.
- "Make the jsfiddle not wrap the stuff onload. Change
onLoad
to no wrap ( body or head )."
My particular example isn't wrapped in onLoad
(at least, I don't think that it is). Anyways, thanks!