0

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!

2 Answers 2

1

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>

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

Comments

1

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;');
});

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.