1

I have two scripts:

<script src="../js/createopp.min.js"></script>
<script src="../js/validation.min.js"></script>

This following line is in the first script, calling a function in the other one:

$('#places').blur(function(){checkPlacesAvailable()});

If I rewrite this as

$('#places').blur(checkPlacesAvailable());

I get a "not defined" error on the function. But I see many examples where the second format is used. Is there something obvious stopping the second version from working in my case?

magnol
  • 344
  • 3
  • 15
  • 4
    In the second case, the `checkPlacesAvailable` method is called immediately, where as in the first case, it's only called on a `blur` event. – Zenoo Aug 19 '19 at 13:03
  • 4
    You may be confusing the second case with `$('#places').blur(checkPlacesAvailable);` – Lee Taylor Aug 19 '19 at 13:04
  • Thanks for the interesting and useful comments to explain why the version with "function()" is needed. But I've obviously confused you all with the wording of my question. Nobody has yet said why I get a "not defined" error in one case but not the other? – magnol Aug 19 '19 at 13:46
  • @Lee Taylor: How does your example function differently? – magnol Aug 19 '19 at 15:13

2 Answers2

2

You should pass function references to event handlers like that.

$('#places').blur(function(){checkPlacesAvailable()});

"is" "equivalent" to this

$('#places').blur(checkPlacesAvailable);

Note that it is not exactly the same because of scopes and all that but most of the times you can pass it in the second manner

Carlos Sá
  • 602
  • 3
  • 10
  • It may be that it is something to do with the scope that's causng me confusion and may also be the cause of JS not recognising the function name. Could you say more? – magnol Aug 19 '19 at 15:11
  • @magnol If JS isn't recognizing the function name then you probably haven't defined it yet. Basically in my first example I'm not accessing the reference `checkPlacesAvailable` until the event is fired, whilst in the second example I'm accessing it immediately. You're getting an error because the `checkPlacesAvailable` reference is only set to a function at a latter time in code execution You can check [this fiddle](https://jsfiddle.net/oe31n7Lu/6/) where I represent both examples check the console – Carlos Sá Aug 19 '19 at 17:01
1

This code:

$('#places').blur(checkPlacesAvailable());

start your function immediatly. If you don't want to write "function" you can make this:

$('#places').blur(() => checkPlacesAvailable());
Iiskaandar
  • 394
  • 2
  • 7