Reputation: 383
What I want is that the user can select text in my html document and that the selected text if not already will set to bold. If it is already bold then it would be set back to regular. I found a example on stackoverflow here and wanted to try this out.
This my test code:
<html>
<head>
<title>Test</title>
</head>
<body>
<script type="text/javascript" language="JavaScript">
function toggleBold() {
var range, sel;
if (window.getSelection) {
// Non-IE case
sel = window.getSelection();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
document.execCommand("bold", false, null);
document.designMode = "off";
} else if (document.selection && document.selection.createRange &&
document.selection.type != "None") {
// IE case
range = document.selection.createRange();
range.execCommand("bold", false, null);
}
}
</script>
<div onselect="toggleBold()">This is a test.</div>
</body>
</html>
When I'm testing this in chrome, safari or whatever nothing happens.
I'm not a javascripter so I don't know how to debug this.
Upvotes: 0
Views: 339
Reputation: 27614
Try onclick()
function
<div onclick="toggleBold()">This is a test.</div>
Upvotes: 3
Reputation: 11872
An alternative answer to keep away from the inline JavaScript. Your toggleBold()
function does work, although it's not actioning upon any event, as select
event works on mostly elements that are actioned from <form>
elements.
<span>Here is some text</span>
<script>
/**
* Listen for any 'mouseup' event, which is actioned
* after the mouse click is released after a selection.
**/
window.addEventListener( 'mouseup', toggleBold, false );
function toggleBold() {
//Toggle's the text.
}
</script>
Upvotes: 1
Reputation: 324
onSelect is only defined on input and textarea objects. Try to use onMouseUp.
<div onmouseup="toggleBold()">This is a test.</div>
Example: Fiddle
Upvotes: 2
Reputation: 1162
Use onMouseUp event
<div onMouseUp="toggleBold()">This is a test.</div>
Upvotes: 1