1

I have this piece of code. If conditions are met i create a button "Show on Map". Now I need to run onclick event on created button that reddirects the user to a map on new URL. I tried with "window.location" in function go_to_map but it doesn't work. Any help?

function coordinates_Conv (d, m, s) {
    return d + m / 60 + s / 3600;
}

function alarm(){
    var lat_d = parseInt(document.getElementsByClassName("lat_deg")[0].value);
    var lat_m = parseInt(document.getElementsByClassName("lat_min")[0].value);
    var lat_s = parseInt(document.getElementsByClassName("lat_sec")[0].value);
    var lon_d = parseInt(document.getElementsByClassName("lon_deg")[0].value);
    var lon_m = parseInt(document.getElementsByClassName("lon_min")[0].value);
    var lon_s = parseInt(document.getElementsByClassName("lon_sec")[0].value);
    if ((coordinates_Conv (lat_d,lat_m,lat_s)<=90) && (coordinates_Conv (lat_d,lat_m,lat_s)>=0) && (coordinates_Conv (lon_d, lon_m, lon_s)<=180) && (coordinates_Conv (lon_d, lon_m, lon_s)>=0)){
    document.getElementById("vypocet").innerHTML= String(Math.round(coordinates_Conv (lat_d,lat_m,lat_s)*1000)/1000) + "<br>" + String(Math.round(coordinates_Conv (lon_d, lon_m, lon_s)*1000)/1000);

    var show_map = document.createElement("button","map");
    show_map.setAttribute("id","map");
    show_map.setAttribute("onclick", go_to_map);
    show_map.innerHTML = "Show on map";
    document.body.appendChild(show_map);

    }
    else {
        alert("Invalid input");
    }
}
function go_to_map(){
    var targetMap = "https://www.mapurl.com/"
    window.location=targetMap;
}
  • try `window.location.href = ` – garglblarg Nov 18 '16 at 15:52
  • Possible duplicate of [adding onclick event to dynamically added button?](http://stackoverflow.com/questions/6956258/adding-onclick-event-to-dynamically-added-button) – Mahi Nov 18 '16 at 15:53

2 Answers2

1

Your onclick handler never gets called in the first place.

To set it handler correctly, set the element's onclick directly:

show_map.onclick = go_to_map;
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
0

You need to replace show_map.setAttribute("onclick", go_to_map); with show_map.onclick = go_to_map;. This is because onclick is an event and not an attribute.

Gavin
  • 4,365
  • 1
  • 18
  • 27
  • Setting `window.location` works just fine. Try it in your browser console: `window.location = 'http://google.com'`. [MDN even demonstrates it this way in their examples](https://developer.mozilla.org/en-US/docs/Web/API/Window/location#Example_1_Navigate_to_a_new_page). – TimoStaudinger Nov 18 '16 at 15:59
  • that's a shorthand that _might_ not do what you would expect, even the mdn states: "in most cases: location = 'http://www.example.com' is a synonym of location.href". – garglblarg Nov 18 '16 at 16:03