Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing a function in jsfiddle

Sorry, really stupid question here. If you post a question about javascript or jquery, people often say - create a jsfiddle.

So, I did. My question will be about getting divs to slide up using jquery but, I can't even get a basic javascript function to run in jsfiddle.

http://jsfiddle.net/ubq6E/

<div onclick="showit()">Hello</div>
function showit()
{
alert('hi');
}

A div, click on it to call a javascript function, but jsfiddle says the function is not defined. Can you not do this in jsfiddle?

like image 574
Martin Smellworse Avatar asked Mar 21 '13 09:03

Martin Smellworse


People also ask

How do I run a function in JSFiddle?

With JSFiddle, you can write code in the JavaScript box and then execute it by clicking the Run button on the menu bar at the top of the JSFiddle page.

Is JSFiddle an IDE?

JSFiddle is an online IDE which is designed to allow users to edit and run HTML, JavaScript, and CSS code on a single page.

How do I search JSFiddle?

Easily enter any jsfiddle username, then search/filter in either jsfiddle title or text (or leave empty to just show all), and then shows fiddle results in a table with details and clickable links. Should be useable by anyone without the need to install anything.

How do I get JSFiddle code?

In the very own, for example, http://jsfiddle.net/Ua8Cv , if you just type the extra /show at the address bar and hit enter (followed by the browser show source code shortcut) to get the source.


1 Answers

You've selected the default onLoad option in jsfiddle.

This causes the site to wrap your entire code within a callback function, meaning that your showit function is not a global function as required by DOM0 inline event handlers.

There are several work arounds, in my personal order of preference:

  1. don't use DOM0 inline handlers, they're really old school - look into element.addEventListener() instead and separate your markup from your JS.

  2. use window.showit = function() { ... } instead to force your function to appear in the global name space.

  3. select one of the "no wrap" options

like image 194
Alnitak Avatar answered Oct 16 '22 11:10

Alnitak