0

I want to be able to change the OnClick event when a other part of the page Javascript has been selected. So that the OnClick corresponds with that.

<a href="#" id="black" onClick="javascript:changetxt
  ('#333');">Black</a>

Can turn into:

<a href="#" id="black" onClick="javascript:changetxt
  ('#666');">Black</a>
2
  • What have you tried? Did it work? If not, why not? Also, where does PHP fit into all this? Commented May 26, 2012 at 21:01
  • I tried the element.setAttribute("onclick","code to run"); and works. But I have to use getElementById which is a problem because I want to select all IDs. I'd use class, but the setAttrirbute wont work that way. Commented May 26, 2012 at 21:42

1 Answer 1

3

You can change onclick just like any other attribute.

// Works, but not recommended:
element.setAttribute("onclick","code to run");

// Better:
element.onclick = function() {code to run};

// There are options with event handlers too, but they're needlessly complicated

Note that you do NOT need javascript: at the start of an event handler. The only reason you don't get an error is because it is parsed as a label called javascript, which is fine.

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

1 Comment

An expansion: javascript: is only used to specify the JavaScript protocol in a URI, e.g. <a href='javascript:alert("icky")'>icks!</a>).

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.