2

Is there any way to prevent inline onclick attributes from an external js file?

<button id="myButton" type="button" onclick="alert('Dont show me please!');" >Click me</button>

In script.js:

var mybutton = document.getElementById("myButton").addEventListener("click", preventIt);

function preventIt(e){
  console.log('click event...');
  e.preventDefault();
}

Assume that we can't change html markup.

4 Answers 4

4

You could remove the onclick attribute like so:

document.getElementsByID("myButton").removeAttribute("onclick");
Sign up to request clarification or add additional context in comments.

Comments

2

Remove

window.onload=function() {
  document.getElementById("myButton").removeAttribute("onclick");
}

or replace:

window.onload=function() {
  document.getElementById("myButton").onclick=function() {
     alert("No you cannot");
  }
}

Comments

2

I think that the fastest way to do this is to just clone the node, which will remove all event listeners:

var old_element = document.getElementById("btn");
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);

Just be careful, as this will also clear event listeners on all child elements of the node, so if you want to preserve that you'll have to resort to explicitly removing listeners one at a time. and add button after that.

2 Comments

Interesting alternative
your way is also pretty.
0

i think this should work

function preventIt(e) {
   e = e || window.event;
   console.log(e.type);
   if (e.preventDefault) {
      e.preventDefault();
   } else {
      e.returnValue = false;
   }
   return false;
}

var myButton = document.getElementById("myButton");
myButton.addEventListener('click', preventIt);

1 Comment

Never start an answer with "I think" :)

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.