user1480139
user1480139

Reputation: 383

set selected word in bold in html document

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

Answers (4)

Jaykumar Patel
Jaykumar Patel

Reputation: 27614

check jsFiddle

Try onclick() function

<div onclick="toggleBold()">This is a test.</div>

Upvotes: 3

MackieeE
MackieeE

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>

Demo Fiddle: http://jsfiddle.net/QRypZ/

Upvotes: 1

CodeCarvings
CodeCarvings

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

Anand Natarajan
Anand Natarajan

Reputation: 1162

Use onMouseUp event

<div onMouseUp="toggleBold()">This is a test.</div>

Upvotes: 1

Related Questions