<div style="float:left;width:100px;height:100px;border:1px solid black;" onclick="this.innerHTML = 'TEST';"></div>
When I click on this box Firefox selects the text. If the div is not empty the text is not selected. Why is that?
Demo
People can struggle and complain about innerHTML not working. Such things usually occur because of human error, when strings are not appropriately defined, or there are some mistakes in JavaScript code.
'innerHTML' Presents a Security RiskThe use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.
I don't know what the reason is, but there's a simple solution. Put a
in the div. Your code would look like this:
<div style="float:left;width:100px;height:100px;border:1px solid black;" onclick="this.innerHTML = 'TEST';"> </div>
Demo
That could be the onclick. You can try timeout (disclaimer: inline code is not recommended):
<div id="testDiv" style="float:left;width:100px;height:100px;border:1px solid black;"
onclick="setTimeout(
function() {
document.getElementById('testDiv').innerHTML = 'TEST';
}
,10)"></div>
UPDATE: But is is not the onclick - seems the click is cached by Fx and still executed after the timeout - I will leave the answer to show that it did not work :)
DEMO
It's possibly down to the way in-browser selection handling works. If you imagine when you "click" you create a collapsed selection in that location (all selections have a start and end point) - this collapsed selection probably wraps the start and end of the div (from a DOM perspective). Next the code injects some content directly inside the div which pushes the selection end point till after the new text... when the browser redraws, the text selection magically appears. Adding the
probably means FireFox has somewhere else to place the collapsed selection so it isn't wrapping the div.
If you've ever tried building your own browser-based WYSIWYG Editor, you'll know how complicated the whole selection process is to code.
You could probably get around the same problem by using .blur() method, or some of FireFox's actual selection methods... although the
method is elegant in it's simplicity.
Very odd bug to discover btw ;)
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