0

I can get $("#demoMapPut").click(function(){ console.log("Success!");}); to work as an event handler in an HTML page.

However if I change it to:

$("#demoMapPut").click(onPutMap);

    var onPutMap = function(evt){
        console.log("This is a Test");
    }

it doesn't seem to anymore. Can someone point out if I've done something wrong? This is just a simple example where I click on an HTML button with id="demoMapPut"and a message appears in the console.

LeDoc
  • 935
  • 2
  • 12
  • 24
  • define onPutMap before invocation – mplungjan Feb 07 '14 at 18:44
  • Or change the function definition to `function onPutMap(evt){...` http://stackoverflow.com/a/9423803/1095101 – azeós Feb 07 '14 at 18:46
  • See [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) – Satpal Feb 07 '14 at 18:48

1 Answers1

1

Simple. Declare the function before the handler.

var onPutMap = function(evt){
  console.log("This is a Test");
}

$("#demoMapPut").click(onPutMap);

Now, let's mix in some best practices (and a touch of my OCD).

First, it is good to name your handlers based on what they handle. So not 'onPutMap' but 'onClickMapPut' would be better. Also, I recommend also using 'on' instead of the click shortcut. Also, it is good to always use single quotes for string declarations. So my OCD rewrite looks like this:

var onClickDemoMapPut;

onClickDemoMapPut = function ( event ) {
  console.log( 'This is a test' );
}

$( '#demo-map-put' ).on( 'click', onClickDemoMapPut );

I know these are all simple, and maybe silly looking, but some can save a lot of time. For example, look at the handler name 'onClickDemoMapPut': convention tells me exactly what to call it. This helps reduce silly errors and cognitive overhead.

Also, there are x-browser issues surrounding mixed-case class and ID names. It is wise to use only lower case for these purposes. Also, the class name has dashes as a form of namespacing and avoiding mixed-case.

Cheers, and good luck!

Michael Mikowski
  • 1,269
  • 1
  • 10
  • 21