javascriptonclickdom-eventsunobtrusive-javascript

Can unobtrusive Javascript event be used in document head?


There are a few examples on unobtrusive events for pure JS. Most of questions in this subjects are practically answered with jQuery solutions. I wonder how this simple example works. As I tested, this function inside the document head perfectly works for click on the entire document

document.onclick=function(){alert("OK");}

but this does NOT work for click on <div id="test">CLICK</div>

document.getElementById("test").onclick=function(){alert("OK");}

How to capture click on an element for unobtrusive JS function?

UPDATED QUESTION: Following the answer by ascii-lime, how unobtruive Javascript events can be place in the document 'head`?


Solution

  • It works just fine.

    Make sure your script is running after your <div> exists, either by putting your script after the <div>, or by running it in a window.onload event handler.

    Alternatively you can attach the onclick to the document (since the document definitely exists before your script runs) and then detect which element was clicked like this:

    document.onclick = function(e){
        e = e || window.event;
        if(e.target.id == 'test')
            alert('OK');
    }