1

I have problem with this code:

    var xButton = document.createElement("a");
    xButton.className = "cXButton";
    xButton.href = "#";
    xButton.onclick = "closePanel()";
    xButton.innerHTML = "X";

While "closePanel()" is a function I already wrote. I used Firebug and found out that "onclick" attribute doesn't appear in a tag. I saw some threads where instead of the name of the function there is it's implementation (function closePanel(){...}). This is not what I'm looking for.

Any suggestions how to solve it?

1

1 Answer 1

6

Your have two problems in your original code:

  • "closePanel()" is a string.
  • closePanel() attempts to (or would if it wasn't a string) call the function and assign it's output to xButton.onclick

It should be this instead:

xButton.onClick = closePanel;

This will assign a reference to the function closePanel() to xButton.onClick, calling closePanel() when the xButton.onClick event is triggered.

Remember you can use this inside the declaration of closePanel() to reference the clicked element.

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

1 Comment

It works, though it onClick attribute doesn't appear in Firebug.

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.