Search code examples
javascriptdom-eventspreventdefault

How to use Javascript event preventDefault() function inside a function?


I want to do something like this:

HTML code:

<a id="myAnchor" href="#" onclick="myfun()">Click Me </a>

JavaScript code:

function myfun(event) {
    event.preventDefault();
    alert("OK");
}

I know we can code like below :

document.getElementById("myAnchor").addEventListener("click", 
function(event){
   event.preventDefault();
   alert("OK");
});

But I want something like above mentioned


Solution

  • Pass event in the function call in the element:

    function myfun(event) {
        event.preventDefault();
        alert("OK");
    }
    <a id="myAnchor" href="#" onclick="myfun(event)">Click Me </a>