Jonny
Jonny

Reputation: 23

Is there a way to use onclick without really onclick event?

I am having this code:

<a href="" onclick="return false;" class="submitme">Add</a>

is there any way to make an alert whenever the user will press this button without changing the code or adding onclick event?

Upvotes: 1

Views: 202

Answers (3)

freefaller
freefaller

Reputation: 19953

As the OP states that they are not allowed to change the HTML, and that jquery is not available to them.

Not having an 'id' on the link makes life very difficult. So the following code presumes the link is the very first one on the page...

Place this javascript into the <head></head> section of your page...

<script type="text/javascript">
  window.onload = function() {
    document.getElementsByTagName("a")[0].onclick = function() {
      alert("Hello World");
      return false;
    }
  }
</script>

See Live JSFiddle Demo

Upvotes: 0

Niko
Niko

Reputation: 26730

You can simple overwrite the attribute with JavaScript:

// Select the targeted element(s), in this case the first <a> element
// Note: You will need to replace this by a code that works
//       for your actual markup!
document.getElementsByTagName("a")[0].onclick = function() {
    alert("hi");
    return false;
}​​​;

Demo: http://jsfiddle.net/WNZAP/

Upvotes: 1

Karl Laurentius Roos
Karl Laurentius Roos

Reputation: 4399

It's not possible to trigger an action without an event. But if I get your question right you want to trigger an alert without changing the HTML.

The easiest way would be by using a JavaScript library like jQuery. So load the library either by downloading it and placing it in your project or through the Google CDN:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

And then do something like this:

<script type="text/javascript">
$(document).ready(function(){
    $(".submitme").click(function(){
        alert("hello world");
    });
});
</script>

Upvotes: 0

Related Questions