Reputation: 3269
I'm trying to override all 'a' tags in a document with a specific class to prevent their default behavior and send a javascript alert. Here is my code so far:
$('.specific-class').click(function (event) {
event.preventDefault();
event.onclick('alert("hello world")');
});
This code stops the links from firing, as it should, but it doesn't send my 'hello world' message.
Does anyone know the appropriate syntax to make the alert fire when the links are clicked? Let me know if I can provide any additional information!
Upvotes: 0
Views: 47
Reputation: 775
Your error was using event.onclick();
instead of just alert()
which will fire when you click
Here is the snippet:
$('.specific-class').click(function (e) {
e.preventDefault();
alert("hello world");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="specific-class">hi you, click me.</div>
Upvotes: 1
Reputation: 87203
Use alert
inside handler as this function will be executed on the click of anchor.
$('.specific-class').click(function (event) {
event.preventDefault();
alert("hello world");
});
Or you can also update the onclick
attribute value on page load
$(document).ready(function() {
$('.specific-class').attr('onclick', 'alert("Hello World!"); return false;');
});
Upvotes: 1