Why does the "click" callback not invoked the first time after some text is entered into the input like in this fiddle?
var app = {};
app.controller = function(){
this.data = m.prop("");
this.click = function(){
alert("button clicked");
};
};
app.view = function(ctrl){
return m("html", [
m("body", [
m("div", [
m("p", ctrl.data()),
m("input[type=text]", { onchange: m.withAttr("value", ctrl.data) }),
m("button", { onclick: ctrl.click }, "Click")
])
])
]);
};
m.module(document, app);
If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.
span element has onclick event to handle mouse clicks.
The Click event is raised when the Button control is clicked. This event is commonly used when no command name is associated with the Button control (for instance, with a Submit button).
The input's onchange event is triggered on mouse down, which causes the view to redraw, thus making the button move down. The click event is triggered on mouse up (try clicking and holding down the mouse button without typing anything to see what I mean). Usually a fast click has a ~200ms gap between the underlying onmousedown and the onmouseup events due to the physical distance between rest and pressed position on the mouse button's mechanical switch.
So basically, what's happening is:
1 - mouse button gets pressed, triggers onchange
2 - view redraws, and moves button down to make room for the text in the <p>
3 - some time later, the mouse button gets unpressed, triggering the onclick
4 - the event looks at the current position of the mouse (which is on top of the <p>
now), so it does not trigger the event on the button
You can see that this is the case by typing something, then clicking and holding down the mouse button, then dragging the cursor over the button again.
In order to avoid this problem, you can use a onmousedown instead of a onclick so that both onchange and onmousedown happen within the same animation frame, or if the UI permits, you can move the <p>
below the button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With