Javascript: problems with click event when using requestAnimationFrame
function render() {
element.innerHTML = "some text";
requestAnimationFrame(render);
}If now on the element (or the entire document) hang an onclick event handler, and then click on the text, then ... nothing happens.
Learn More
So, create a div:
Stretch it to full screen:
#main {
width: 100%;
height: 100%;
position: absolute;
cursor: default;
background-color: #CCC;
font-size: 30vh;
}Now the code:
function render() {
document.getElementById("main").innerHTML = "click here";
requestAnimationFrame(render);
}
document.body.addEventListener("click", function(e) {
console.log("click");
});
render();You can play with the code here .
The result is as follows:
- when you click on the text nothing happens, the event does not occur
- when you click in any other part of the main event occurs, the console displays "click"
Additional points:
- if you remove the font, and leave just the text, then the click occurs
- if you replace font with span, then the click still doesn’t happen
- if you comment out the string requestAnimationFrame (render), then the click occurs
- other events, such as mousemove, occur as they should, both above and without text
Why is this needed?
The question does not entirely relate to the topic, but nonetheless: why do we need such code at all, what practical application?
Answer: consider this as a puzzle at the Olympics. Suppose you want to create a page filled with random characters, each of which randomly changes color. When clicking on a symbol, display it in the console.
Create a character class that has a getText method that returns a character of the current color, something like this:
// some code
symbol.prototype.getText = function() {
return "" + this._text + "";
};Then, in the requestAnimationFrame, we insert the recount of colors and the output of all characters in turn on the screen.
It remains to add click processing.
Solution
The first thing that came to mind, the decision "on the forehead." Add another div:
The same size as main, but transparent and with a large z-index:
#click {
width: 100%;
height: 100%;
position: absolute;
cursor: default;
opasity: 0;
z-index: 100;
}After that, a click on the text and outside it works fine.
Of the other options, only the following comes to mind. Add a span element with a unique index for each character in advance, and in requestAnimationFrame just change the color via document.getElementById ("span_id"). Style.color. It seems to me that this option is too cumbersome.
Afterword
I did not understand what is the specific reason for this click behavior. If there are people who understand what this is, please share wisdom. Thanks!
Update
As Zibx pointed out in the comments, for the click event to take place, the mousedown and mouseup events must occur on the same element. Since innerHTML is constantly being updated in this case, this does not happen.