Onclick Event Function in JavaScript

Javascript function to add onclick event

This is a classic issue related to JavaScript 'closure' concept.

Problem

In your loop for (i = 1; i < totalPages + 1; i++), the variable i is bound to the same variable, and after the loop i = 3, thus, when triggering onclick the variable i is bound to value 3, and leads to '3 in every button'.

This article may help you understand the problem as well.

Simple ES6 fix

We only need to use let/const keyword in the loop condition. Check create_pagination_fix1 in the code below.

Reason: docs In for(const i;;){} or for(let i;;){}, i can get a new binding for every iteration of the loop, as each iteration is a new lexical scope. If you use var as for (i = 1 is equal to for (var i = 1, i would get the same binding when you click the button later.

Fix using closure

Please check create_pagination_fix2 in the code below. There have been many posts about the usage of JavaScript closure in the loop, I'd refer you to this post for a nice explanation.

You can run the code snippet below and see the difference between each method. My changes are quite little.

var pageItemDiv = document.getElementById("app");

function create_pagination_problematic(totalPages, hasNext, hasPrevious) {
if (document.querySelector(".page-number") != null) {
document.querySelectorAll(".page-number").forEach((e) => e.remove());
}

for (var i = 1; i < totalPages + 1; i++) {
var pageItemNumber = document.createElement("button");
pageItemNumber.id = `${i}`;
pageItemNumber.innerHTML = `${i}`;
pageItemNumber.onclick = () => console.log(i);

pageItemDiv.appendChild(pageItemNumber);
}
}

function create_pagination_fix1(totalPages, hasNext, hasPrevious) {
if (document.querySelector(".page-number") != null) {
document.querySelectorAll(".page-number").forEach((e) => e.remove());
}

// only change is here, use let instead of var
for (let i = 1; i < totalPages + 1; i++) {
var pageItemNumber = document.createElement("button");
pageItemNumber.id = `${i}`;
pageItemNumber.innerHTML = `${i}`;
pageItemNumber.onclick = () => console.log(i);

pageItemDiv.appendChild(pageItemNumber);
}
}

function getOnclick(i) {
return function () {
console.log("Onclick: " + i);
};
}

function create_pagination_fix2(totalPages, hasNext, hasPrevious) {
if (document.querySelector(".page-number") != null) {
document.querySelectorAll(".page-number").forEach((e) => e.remove());
}

for (var i = 1; i < totalPages + 1; i++) {
var pageItemNumber = document.createElement("button");
pageItemNumber.id = `${i}`;
pageItemNumber.innerHTML = `${i}`;
// only changing here: use closure to keep reference to value i
pageItemNumber.onclick = getOnclick(i);

pageItemDiv.appendChild(pageItemNumber);
}
}

create_pagination_problematic(3);
pageItemDiv.appendChild(document.createElement("br"));
pageItemDiv.appendChild(document.createElement("br"));
create_pagination_fix1(3);
pageItemDiv.appendChild(document.createElement("br"));
pageItemDiv.appendChild(document.createElement("br"));
create_pagination_fix2(3);
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>

<body>
<p>
First row is wrong implementation, when second and third rows are fix.
</p>
<div id="app"></div>

<script src="src/index.js"></script>
</body>
</html>

Handling "onclick" event with pure JavaScript

All browsers support this (see example here):

mySelectedElement.onclick = function(e){
//your handler here
}

However, sometimes you want to add a handler (and not change the same one), and more generally when available you should use addEventListener (needs shim for IE8-)

mySelectedElement.addEventListener("click",function(e){
//your handler here
},false);

Here is a working example:

var button = document.getElementById("myButton");
button.addEventListener("click",function(e){
button.disabled = "true";
},false);

And html:

<button id='myButton'>Hello</button>

(fiddle)

Here are some useful resources:

  • addEventListener on mdn
  • The click event in the DOM specification
  • Click example in the MDN JavaScript tutorial

Onclick Event Javascript & JQuery

Is this what are you looking for?

function one(){var btn = "<button type='submit' id='processReceipt' class='btn btn-primary' onclick='form_new_receipt()'>Submit</button>";$('#showGrower').append(btn);}
$(document).on('click', '#processReceipt', function() { one()});
function form_new_receipt(a) { alert('before function');}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="showGrower"></div><button id="processReceipt" type="button">Click me</button>

onclick event function in JavaScript

Two observations:

  1. You should write

    <input type="button" value="button text" />

    instead of

    <input type="button">button text</input>
  2. You should rename your function. The function click() is already defined on a button (it simulates a click), and gets a higher priority then your method.

Note that there are a couple of suggestions here that are plain wrong, and you shouldn't spend to much time on them:

  • Do not use onclick="javascript:myfunc()". Only use the javascript: prefix inside the href attribute of a hyperlink: <a href="javascript:myfunc()">.
  • You don't have to end with a semicolon. onclick="foo()" and onclick="foo();" both work just fine.
  • Event attributes in HTML are not case sensitive, so onclick, onClick and ONCLICK all work. It is common practice to write attributes in lowercase: onclick. note that javascript itself is case sensitive, so if you write document.getElementById("...").onclick = ..., then it must be all lowercase.

Javascript - Calling a function for an onClick event

First of all, thanks for taking the time to reply.

In the end, I took a look at the following answer : https://stackoverflow.com/a/21477793/3186538 and I ended up with this code :

<html>

<head>
</head>

<body>
<script>
// Display text function
function showAlert(text) {
alert("Called in showAlert: " + text);
}
// But for the previous function to work, we must make sure that it is loaded after the rest of the DOM
window.onload = function() {
document.getElementById("aTag").onclick = function fun() {
showAlert("Hello World");
}
}
</script>

<table>
<tr>
<td><a href="javascript:void(0)" id="aTag">TEST</a></td>
</tr>
</table>
</body>

</html>

Now, when I click on the hyperlink, I do get a dialog box showing the Hello World message.

Thanks again to everyone (and, of course, SO).

window.onclick = function(event) only works for first item

use

window.addEventListener("click", function(event) {
});

instead of

window.onclick = function() {
}

https://jsfiddle.net/qsL76mx6/

Onclick event won't recognise function

It seems the name accept is causing trouble. See this jsfiddle.

Rename your function and put it in the global scope.

JavaScript onClick Event Function

Your selector returns an array-like object known as a HTMLCollection not a single element.

Try,

document.getElementsByClassName("esg-filterbutton")[0].addEventListener("click", myFunction);

Notice I'm grabbing the first element in the array?

Also I removed the . before the name of the class. As you are specifying that you want to select a class in the function, you don't need to put a ..



Related Topics



Leave a reply



Submit