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.

3

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.