0

I'm trying to set an onclick attribute to an anchor like this:

$("a").click(function(e) {
    $(this).onclick = "ItWorks";
    output = "JS onclick attempt: my onclick is: <strong>" + $(this).onclick + "</strong>";
    $(this).prop("onclick", "ItWorks");
    output += "<br />jQuery prop() attempt: my onclick is: <strong>" + $(this).prop("onclick") + "</strong>";
    $(this).attr("onclick", "ItWorks");
    output += "<br />jQuery attr() attempt: my onclick is: <strong>" + $(this).attr("onclick") + "</strong>";

    alert(output);
    e.preventDefault();
}); 

I've tried pure JS, jQuery prop() and attr() functions. As you can see on this example, only .attr() function works as it should.

Can someone tell me what am I doing wrong that the other two attempts return "null" or "undefined"?

4
  • What is the world is $a? also onclick is a bad idea! because it is an event! Commented Oct 21, 2013 at 12:53
  • @epascarello sorry, that was remains from the fiddle, already corrected. I need an onclick because it's for pageTracker purpose Commented Oct 21, 2013 at 12:56
  • 1
    try to use $(this).attr("onclick", "ItWorks()"); Commented Oct 21, 2013 at 12:59
  • the onclick's value have to be passed as a string like this: "pageTracker._trackEvent('category', 'subcategory')" Commented Oct 21, 2013 at 13:15

2 Answers 2

1

$(this).onclick = "ItWorks";

Sets a property on the JQuery object, not the DOM node.

$(this).prop("onclick", "ItWorks");

Sets the property to a string, but it expects a function … and the property does not map directly onto the attribute value as it does for some other properties.

$(this).attr("onclick", "ItWorks");

Sets the attribute to a string, although not one that will do anything when executed as JS.

If you want to set an event handler and are using jQuery, then use the on method, and don't try to test it by examining the attribute value.

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

Comments

1

Why not make it easier:

<a href="javascript:void(0)" onclick='clickEvent("a")'>link</a>
<a href="javascript:void(0)" onclick='clickEvent("a")'>link</a>

function clickEvent(event)  {
   if (event == "a") {
     output = "event a clicked";
   } elseif (event == "b") {
     output = "event b clicked";
   }
   alert(output);

}

1 Comment

unfortunately I cannot use it because there's a lot of rendering objects from xml file and switches and ifs and god only knows what else. Great solution though, thanks!

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.