In Javascript, the onclick function can be used to assign an action to an HTML element when clicked. However, developers often face an issue where the function gets executed immediately upon element creation, even before clicking on it.
In the provided Javascript code, the developer aims to create a link that triggers a function when clicked instead of redirecting to a new page. However, the onclick function (secondFunction) is called immediately due to an incorrect method of assignment.
The error lies in the line:
<code class="js">sentNode.setAttribute('onclick', secondFunction());</code>
Here, the secondFunction() is directly invoked, which means the function runs as soon as it is defined. To resolve this issue, it should be assigned as follows:
<code class="js">sentNode.setAttribute('onclick', secondFunction);</code>
By referencing the function without parentheses, the code assigns the function itself, not its return value. This ensures that the function is executed only when the onclick event occurs.
The correct code should look like:
<br>function startFunction() {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">var sentNode = document.createElement('a'); sentNode.setAttribute('href', "#"); sentNode.setAttribute('onclick', secondFunction); // Assign function reference sentNode.innerHTML = "Sent Items"; // Add new element to parent var parentNode = document.getElementById('parent'); var childNode = document.getElementById('sendNode'); parentNode.insertBefore(sentNode, childNode);
}
By adopting these changes, the onclick function will be called appropriately when the element is clicked.
The above is the detailed content of How to Avoid Premature Execution of Onclick Functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!