Calling function with onclick

2

I can not call a function using onclick, calling it straight from the html tag comes normal but if I call it non-obstructive way no chance I already read several docs I tried in ways and nothing anyone can give a light.

document.getElementById("btSoyouzm").onclick=function(){buscaImagem()};

function buscaImagem(){
        alert("teste do onclick")
}
    
asked by anonymous 31.03.2014 / 21:37

2 answers

4

Try this way dear friend

document.getElementById("btSoyouzm").addEventListener("click", buscaImagem, false); 

function buscaImagem(){
        alert("teste do onclick")
}

Documentation: addEventListener

    
31.03.2014 / 21:40
2

To implement an OnClick event dynamically you need to add this event to the DOM object with addEventListener as in the @SilvioAndorinha response, however this implementation is different in other browsers so you can use a function to do this cross- browser.

Your Role

function buscaImagem(){
        alert("teste do onclick")
}

Javascript addEvent cross-browser

var addEvent = function(elem, type, eventHandle) {
    if (elem == null || typeof(elem) == 'undefined') return;
    if ( elem.addEventListener ) {
        elem.addEventListener( type, eventHandle, false );
    } else if ( elem.attachEvent ) {
        elem.attachEvent( "on" + type, eventHandle );
    } else {
        elem["on"+type]=eventHandle;
    }
};

addEvent(document.getElementById("btSoyouzm"), "click", function(){
  buscaImagem();
});

or

addEvent(document.getElementById("btSoyouzm"), "click",buscaImagem);
    
31.03.2014 / 21:47