2

Probably a very easy question for anyone comfortable with Javascript to answer. Basically I have a tool bar with buttons in an HTML/Javascript/PHP web app I'm working on:

<div class="segmented-control">
  <a class="control-item" onClick='showMapMarkers()'>
    <img src="customIcons/Map.png" width="15" height="20" >
  </a>
</div>

... and you'll see the onClick event calls the function showMapMarkers() which right now is not implemented and I'm only using this:

function showMapMarkers(){
    alert("show map markers");
}

However I get this error:

ReferenceError: Can't find variable: showMapMarkers

If I write the same alert statement directly into the bar button item then the alert works fine so I guess it's a problem of on-click scope not reaching the showMapMarkers() function but I can't understand why.

Any ideas?

GôTô
  • 7,974
  • 3
  • 32
  • 43
user3535074
  • 1,268
  • 8
  • 26
  • 48
  • 1
    I just tried an example at it worked just fine. Are you correctly importing the function? – SantiM May 17 '14 at 15:04
  • 1
    It works fine for me too. The problem isn't with the button. – Michel May 17 '14 at 15:05
  • I'm not sure what you mean with importing the function, could you elaborate a little? To be honest I'm really green with Javascript and it could be that I'm missing some key basic knowledge.... – user3535074 May 17 '14 at 15:10
  • How/where did you test this code? – Felix Kling May 17 '14 at 15:19
  • Im testing in safari and coding in XCODE. This code still fails to run for me (I'm also testing on android). – user3535074 May 17 '14 at 15:23
  • 2
    Most likely `showMapMarkers` is not in global scope. Make sure it is, or use a better way to bind event handlers: http://www.quirksmode.org/js/introevents.html. – Felix Kling May 17 '14 at 15:24

2 Answers2

4

Try this:

showMapMarkers = function(){
    alert("show map markers");
}

Works as expected in my JSFiddle demo http://jsfiddle.net/jq5Cf/

Fr3d
  • 1,235
  • 9
  • 9
  • 1
    The OP's code also works perfectly fine as well: http://jsfiddle.net/Ab6jd/. Could you explain *why* you suggested this approach? – Felix Kling May 17 '14 at 15:17
  • I copy and pasted OP's code into a Fiddle(http://jsfiddle.net/Xvq8W/) myself, and I also got a ReferenceError. – Fr3d May 17 '14 at 15:21
  • That's because you didn't set up the jsFiddle correctly. See http://stackoverflow.com/a/5830423/218196. – Felix Kling May 17 '14 at 15:22
0

It was indeed a problem of the scope of the function and the onClick event.

After seeing confirmation that the actual code worked correctly I tried moving the function in to the same div as the button and the function could be called.

user3535074
  • 1,268
  • 8
  • 26
  • 48