-1

HI i am new to js and html, i am trying to add button on html through js and on button click i tried show alert message

here My code

topobutton=document.createElement("button");            
topobutton.innerHTML="Topo";
topobutton.value="Topo";
topobutton.type="button";
topobutton.id="Topo";
topobutton.style.margin="2px";                      
document.body.appendChild(topobutton);
topobutton.onclick=showMap("topo"); 

function showMap(mapname){
            alert(mapname)};

when page is reloading it shows the alert message and on button click not responding why?

1 Answers1

-2

EDIT

You calling the function instead of add reference / event listener.

topobutton.onclick = () => { showMap("topo") }

// OR

topobutton.onclick = function() { showMap("topo") }

// OR

topobutton.addEventListener('click', function() { showMap("topo") });
BadPiggie
  • 5,471
  • 1
  • 14
  • 28