📜 ⬆️ ⬇️

Javascript: problems with click event when using requestAnimationFrame

Suddenly faced with a funny problem. Briefly, the essence can be described as follows. Suppose you use requestAnimationFrame to dynamically change the color of the text, like this:

function render() { element.innerHTML = "<font color='#555'>some text</font>"; requestAnimationFrame(render); } 

If you now hang an onclick event handler on element (or the entire document), and then click on the text, then ... nothing happens.

Read more
')
So, create a div:

 <div id="main"></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 = "<font color='#555'>click here</font>"; requestAnimationFrame(render); } document.body.addEventListener("click", function(e) { console.log("click"); }); render(); 

You can play with the code here .

The result is as follows:


Additional points:


Why do you need it?

The question does not quite relate to the topic, but nevertheless: why such code in general, what practical application?

Answer: consider it as a challenge at the Olympiad. Suppose you want to create a page filled with random characters, each of which randomly changes color. When you click on a symbol, output it to the console.

Create a character class that has a getText method that gives the character of the current color, something like this:

 // some code symbol.prototype.getText = function() { return "<font color='" + this._color + "'>" + this._text + "</font>"; }; 

Then in requestAnimationFrame we interpose color recalculation and a conclusion of all characters in turn on the screen.

It remains to add "click" processing.

Decision

The first thing that came to mind was a head-on decision. Add another div:

 <div id="click"></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, click on the text and outside it works fine.

Of the other options, only the following comes to mind. Add in advance for each character a span element with a unique index, and in requestAnimationFrame just change the color through document.getElementById ("span_id"). Style.color. I think this option is too bulky.

Afterword

I did not understand what the specific reason for this click behavior was. If there are people who understand what's the matter, please share your wisdom. Thank!

Update

As pointed out by Zibx in the comments, for the click event to occur, the mousedown and mouseup events must occur on the same element. Since in this case innerHTML is constantly updated, this does not happen.

Source: https://habr.com/ru/post/279817/


All Articles