Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does firefox select the text when I change innerHTML

<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

like image 541
Tanatos Avatar asked Aug 24 '12 07:08

Tanatos


People also ask

Why innerHTML does not work?

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.

Should I use innerHTML?

'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.


3 Answers

I don't know what the reason is, but there's a simple solution. Put a &nbsp; 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';">&nbsp;</div>

Demo

like image 108
Some Guy Avatar answered Sep 18 '22 10:09

Some Guy


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

like image 45
mplungjan Avatar answered Sep 20 '22 10:09

mplungjan


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 &nbsp; 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 &nbsp; method is elegant in it's simplicity.

Very odd bug to discover btw ;)

like image 41
Pebbl Avatar answered Sep 22 '22 10:09

Pebbl