Chrome toggle checkbox with selection

by Jools Chadwick

HTML

<label>
  <input id="check" type="checkbox"/>
  <span id="label">My checkbox</span>
</label>
<input value="Anything"/>
<div>Something</div>
<input id="fix" type="button" value="Fix"/>

JavaScript

$('#label').on('mousedown',function onMousedown(event){
	if(workaround){
  	clearSelection();
  }
	// Prevent selection of label and unwanted focus shift
	event.preventDefault();
})

// Toggle workaround
var workaround = false;
var $fixButton = $('#fix');
$fixButton.click(function(){
	workaround = !workaround;
  $fixButton.val(workaround?'Break':'Fix');
})

//https://stackoverflow.com/a/14788286/514793
function clearSelection() {
    var sel;
    if ( (sel = document.selection) && sel.empty ) {
        sel.empty();
    } else {
        if (window.getSelection) {
            window.getSelection().removeAllRanges();
        }
        var activeEl = document.activeElement;
        if (activeEl) {
            var tagName = activeEl.nodeName.toLowerCase();
            if ( tagName == "textarea" ||
                    (tagName == "input" && activeEl.type == "text") ) {
                // Collapse the selection to the end
                activeEl.selectionStart = activeEl.selectionEnd;
            }
        }
    }
}