2

i have this code in while loop in JavaScript. As you can see i am adding every loop to with ID page, another divs. Every div has onclick handler which can execute MyFunction with variable. My problem is that, my script onlick runs automatically when my page is loaded. But i need to run MyFunction only if i click on the div.

Code:

document.getElementById("page").innerHTML += "<div style='width:100px; float:left;' onclick='" + MyFunction(variable) + "'>" + AnotherVariable + "</div>";

Thank you

1 Answer 1

3

You're a bit off ... try ...

document.getElementById("page").innerHTML += "<div style='width:100px; float:left;' onclick='MyFunction(" + variable + ")'>" + AnotherVariable + "</div>";

.. if you don't want the function to run.

In particular, look here:

"<div ... onclick='MyFunction(" + variable + ")'>"

UPDATE 1:

"Variable is string." Then, here's the modification:

document.getElementById("page").innerHTML += "<div style='width:100px; float:left;' onclick='MyFunction(\"" + variable + "\")'>" + AnotherVariable + "</div>";
Sign up to request clarification or add additional context in comments.

4 Comments

Specifically, using MyFunction(variable) outside of quotes will run it as soon as the script block is rendered inserting the return value into the concatenated string, this is not we want in this case.
Thank you, but i have new error --> Uncaught SyntaxError: Unexpected token ;... it is saying that is on system.html:1 and first line is <!DOCTYPE html> and there is no ";"
Is variable numeric or a string ... might have to embed quotes if it is a string. use \" ...
Fixed ... should have thought of that. Sorry.

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.