Reputation: 4898
Could someone explain why clicking a button will trigger a browser edit in a contentEditable div but clicking a div that calls the same execCommand does not? In http://jsfiddle.net/GgX8G/3/ I have a button and a div that trigger the same code but only the button executes the bold action:
<div id="boldB">B</div>
<button id="bld">B</button>
$(document).ready(function(){
$('#boldB').click(function() {
document.execCommand('bold', false, null);
alert("clicked the B div");
});
$('#bld').click(function() {
document.execCommand('bold', false, null);
alert("clicked the B button");
});
});
Thanks
Upvotes: 1
Views: 201
Reputation: 9168
When you click on a div
, the currently selected div
loses focus, so there is nothing for the execCommand
function to do. You need to catch the event earlier (e.g. on mouse down), and prevent it. Example here: http://jsfiddle.net/GgX8G/13/
Line by line explanation:
$('#boldB').mousedown(function(e) {
The mousedown event is called before the click event, and before the focus changes, giving us the opportunity to prevent it from changing.
e.preventDefault();
calling preventDefault
on the event object will prevent the subsequent default actions from occuring, i.e. change of focus.
document.execCommand('bold', false, null);
Having done that, you can safely execCommand
on your div
, since it is still in focus and the selection is intact.
Upvotes: 7
Reputation: 159
Here, try this http://jsfiddle.net/GgX8G/7/
the line of jquery you want is this:
$("#boldB").css("font-weight", "bold");
Upvotes: -4