1

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(…)

2 Answers 2

5

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:

Sign up to request clarification or add additional context in comments.

Comments

2

You can also achieve this by adding Event Listener to DOM element.

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

        document.body.appendChild(modalbg); // to place at end of document
        modalbg.innerHTML = "click me";
        modalbg.addEventListener('click', function () {
            alert("Hai");
        })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.