add an onclick event to a div

Is it possible to add onclick to a div and have it occur if any area of the div is clicked.

Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work

If yes then why is the onclick method not going through to my div.

You are assigning a string where a function is expected.

divTag.onclick = printWorking;

There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.

That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener

Leave a Comment