Cláudio Ribeiro Cláudio Ribeiro - 27 days ago 9
Javascript Question

onClick not working inside jsFiddle

I'm having trouble figuring why the onClick event is not working inside jsFiddle. The code is working well on the browser, but when try to port it to jsFiddle I lose the ability to fire the onClick events.

My current code is the following:

For the HTML:

<body>

<button id="find-near-btn" onClick="getMylocation()">
Find companies near me
</button>

<button id="mark-pos-btn" onClick="markMyPosition()">
Mark my position
</button>

<div id="mymap"></div>
<div id="output"></div>

</body>


The js:

function initmap(initialLat, initialLong){
output.innerHTML += "<p>Initialized</p>";

if(!initialLat || !initialLat.length){
initialLat = 38.01693;
}

if(!initialLong || !initialLong.length){
initialLong = -8.69475;
}

var mymap = this.mymap = L.map('mymap',{
center: [initialLat, initialLong],
zoom: 15
});

var osmUrl='http://tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';

L.tileLayer(osmUrl, osmAttrib).addTo( mymap );
}

function getMylocation(){

output.innerHTML += "<p>Obtaining location.</p>";

if(navigator.geolocation){

navigator.geolocation.getCurrentPosition(function (position) {

var lat = position.coords.latitude;
var long = position.coords.longitude;

mymap.setView(new L.LatLng(lat, long), 15);

}, function (error) {
// Get information based on IP
getLatLongByIP();
});
}
}

function getLatLongByIP()
{
$.get("http://ip-api.com/json", function(response) {

handleData(response.lat, response.lon);
}, "jsonp");
}

function handleData(lat, long){
mymap.setView(new L.LatLng(lat, long), 15);
}

function markMyPosition()
{
if(navigator.geolocation){

navigator.geolocation.getCurrentPosition(function (position) {

var lat = position.coords.latitude;
var long = position.coords.longitude;

L.marker([lat, long]).addTo(mymap);

}, function (error) {
switch (error.code) {
case error.PERMISSION_DENIED:
output.innerHTML += "<p>User denied the request for Geolocation.</p>";
break;
case error.POSITION_UNAVAILABLE:
output.innerHTML += "<p>Location information is unavailable.</p>";
break;
case error.TIMEOUT:
output.innerHTML += "<p>The request to get user location timed out.</p>";
break;
case error.UNKNOWN_ERROR:
output.innerHTML += "<p>An unknown error occurred.</p>";
break;
}
});
}
}

initialLat = 38.01693;
initialLong = -8.69475;

initmap(initialLat, initialLong);


The fiddle can be found here. When I click any of the buttons I get nothing. Any idea on how can I make this work?

Answer Source

You need to change your JS code to be inside your page's <body> tag. Use the little cog at the top right of the Javascipt panel and choose No wrap - in <body> under Load type. I already tested this and it works.