Radian Radian - 16 days ago 5
HTML Question

Can't add "onclick" function to div element javascript

Can't add function to element

javascript


the function
modalbg.onclick
not work.

var modalbg = document.createElement("div");

document.body.appendChild(modalbg); // to place at end of document
modalbg.onclick(function () {
alert();
})


Error is:


(index):625 Uncaught TypeError: modalbg.onclick is not a function(…)

Answer

Your syntax:

modalbg.onclick(function () {
            alert();
        })

is wrong, and the reported error-message explicitly tells you why it's wrong: onclick is not a function.

The appropriate syntax, if you must use onclick is:

modalbg.onclick = function () {
        alert();
      };

Although I'd strongly advise you to move away from onclick event-handlers, and use EventTarget.addEventListener() instead, to give:

modalbg.addEventListener('click', alert);

Or:

modalbg.addEventListener('click', function(){
  alert();
});

References:

Comments