Detect if text is bold - javascript

I'm trying to make a WYSIWYG editor, and so far I have it so you can select text and click 'Make Bold' to make the selected text bold. It literally just wraps < b> (no space) tags around the selected text. But my problem is that if I want to un-bold that, my script has some trouble...
So far, here is my script:
<script language="javascript">
function format(tag) //defines function format
{
var editor = document.getElementById('editor');
var txt = '';
var tester = document.getElementById('tester');
if (window.getSelection) //if your browser uses this method of text selection
{
txt = window.getSelection();
}
else if (document.getSelection) //if your browser uses this method of text selection
{
txt = document.getSelection();
}
else if (document.selection) //if your browser uses this method of text selection
{
txt = document.selection.createRange().text;
}
else return; //Return this
matched = editor.innerHTML.match(txt); //Find the selected text in the editor
// if (matched.style.font-weight = "600") {tester.innerHTML = "already bold";} //if the selected text is bold, say 'already bold' DOES NOT WORK
// else {tester.innerHTML = "not bold";} //if it doesn't...
editor.innerHTML = editor.innerHTML.replace(matched,"<"+tag+">"+matched+"</"+tag+">");//Wrap <b> tags around it
}
</script>
<input type="button" value="Make Bold" onmousedown="format('b')">
<input type="button" value="Make Italic" onmousedown="format('i')">
<div id='editor' onclick="javascript:this.designMode='on';" designmode="on" contenteditable="true">Edit Box</div>
<span id="tester">testing span</span>
If you try it out you can type in that box and select text and click Make Bold and it will be bold. Now click Make Bold again but nothing happens. It's just adding another < b> tag around the selected text. I want it to make it un-bold; normal.
How do I do that?
Thanks :)

Messing with the HTML as a string is a bad idea. There are two better options: the first is to obtain the element containing the current user selection and use DOM methods and properties such as parentNode to test if it's bold. This is tricky to do cross-browser. Much easier is to use the execCommand method of document, which will automatically toggle boldness. It's supported in recent versions of all major browsers.
document.execCommand("bold", false, null);
UPDATE
Note that in Firefox (and possibly other browsers), this has no effect unless the document has designMode switched on. Here's a full example. Highlight some text and press Ctrl-B:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
window.onload = function() {
document.designMode = "on";
};
function keyDown(evt) {
if (evt.keyCode == 66 && evt.ctrlKey) {
document.execCommand("bold", false, "");
}
return false;
}
</script>
</head>
<body onkeydown="return keyDown(event);">
<div>I like tea <b>with milk</b></div>
</body>
</html>

Related

How to execute ctrl+c or copy commad using javascript or jquery on button click

Is it possible to execute copy command using click EVENT?
I have some text selected and I want this text to be copied on onClick event, so that I am able to past this text to another page with out using right click or CTRL+C to copy the text.
function copyText(){
var txt = '';
if (window.getSelection)
txt = window.getSelection();
else if (document.getSelection)
txt = document.getSelection();
else return;
document.getElementById("a").value=txt;
allCopied =document.getElementById("a").createTextRange();
allCopied.execCommand("RemoveFormat");
allCopied.execCommand("Copy");
}
but for security reasons most browsers do not allow to modify the clipboard( except Internet explorer).
HTML
<form name="myForm">
<span onclick="copyText(this)" >Text1</span>, <span onclick="copyText(this)" >Text2</span>
<br>
<input name="myField"></input>
JavaScript
function copyText(element) {
document.myForm.myField.value = element.innerHTML;
}
Copy to Clip Board Ctrl+C
$("#text1").click(function(){
var holdtext = $("#clipboard").innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("Copy");
});
use getselection() to get selected text inside a browser window

How to make a content editable div behave like a text area?

I have built an editor that converts markdown to html. Right now I have to use jquery autosize plugin to resize the text area as it grows.
If I use a content-editable div I can bypass it. But the problem with content editable div is that it does not preserve new lines. It inserts a new div every time return key is pressed. This breaks the rendering of markdown to html for my application.
Is there any way I can make a content editable div behave exactly like text area?
After searching for an answer and not finding anything that worked completely I wrote my own jQuery plugin.
https://github.com/UziTech/jquery.toTextarea.js
I used white-space: pre-wrap; and inserted '\n' on enter. That way I can use $("div").text() to get the text and not worry about removing tags and formatting <br/>'s
DEMO:
http://jsfiddle.net/UziTech/4msdgjox/
Edit
After the #Mr_Green comment above, you should have a look at Make a <br> instead of <div></div> by pressing Enter on a contenteditable
The JS code to make it right is :
$(function(){
$("#editable")
// make sure br is always the lastChild of contenteditable
.live("keyup mouseup", function(){
if (!this.lastChild || this.lastChild.nodeName.toLowerCase() != "br") {
this.appendChild(document.createChild("br"));
}
})
// use br instead of div div
.live("keypress", function(e){
if (e.which == 13) {
if (window.getSelection) {
var selection = window.getSelection(),
range = selection.getRangeAt(0),
br = document.createElement("br");
range.deleteContents();
range.insertNode(br);
range.setStartAfter(br);
range.setEndAfter(br);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
return false;
}
}
});
})
;
You can intercept the Enter key press and replace it with a <br> with Javascript :
$(function(){
$("#editable").keypress(function(e) {
if (e.which == 13) {
e.preventDefault();
if (document.selection) {
document.selection.createRange().pasteHTML("<br/>");
} else {
$(this).append("<br/>");
}
}
});
});

Text Input Selection not working in IE9

I am trying to get the user selected text in a text input when a button is clicked. This what I am trying:
<head>
<script type="text/javascript">
function GetSelectedText () {
if (window.getSelection) { // all browsers, except IE before version 9
var range = window.getSelection ();
alert (range.toString ());
}
else {
if (document.selection.createRange) { // Internet Explorer
document.getElementById("foo").focus();
var range = document.selection.createRange();
alert (range.text);
}
}
}
</script>
</head>
<body>
<button onclick="GetSelectedText ()">Get the selected text!</button>
<input type = 'text' id = 'foo' />12345
</body>
It works as expected in all browsers, except IE9. In IE9, if you select some text from the 12345 chunk and press the button, the selected text is alerted all right. However, if you type something in the text input, select some of it, and click the button, a blank alert is generated.
Can anyone tell me how do I get it working in IE9? And is there any way to get the cursor position of the selection start as well (something like Mozilla's selectionStart)? Iam looking for Javascript solution, without Rangy or other related jQuery libraries..
Text inputs and textareas have a separate selection API, namely selectionStart and selectionEnd properties of the input itself. These are not supported in IE <= 8, but you already have the alternative for those.
Here's an implementation of your GetSelectedText() function that works in all major browsers:
Demo: http://jsfiddle.net/UK8gA/
Code:
function GetSelectedText() {
var selectedText = "";
var input = document.getElementById("foo");
var sel, val = input.value;
input.focus();
if (typeof input.selectionStart == "number") {
selectedText = val.slice(input.selectionStart, input.selectionEnd);
} else if ( (sel = document.selection) && sel.createRange) { // IE
var range = document.selection.createRange();
selectedText = range.text;
}
alert(selectedText);
}
You can take a look at the jQuery Caret plugin: jCaret
// Get start pos in intput box with id="box1"
$("#box1").caret().start
// Get end pos
$("#box1").caret().end
// Get selected text
$("#box1").caret().text
It all looks good except that the line "document.getElementById("foo").focus();" does not appear to be necessary and is probably why the browser is unable to detect the highlighted text. Try to remove it and see what you get.

How do I highlight and change a part of a textarea

I have a textarea where when the user selects and presses enter I want it to change to something else. For example I have a textarea, when a user selects something like NY, I want those two letters to change to NY
Here's a fiddle but I'm lost
I have something like :
$('textarea').html('I live in NY and it\'s a great place to live');
$(window).click(function(){
var selection = selectedText();
console.log(selection);
});
function selectedText() {
var ret = '';
if (window.getSelection){
ret = window.getSelection();
} else if (document.getSelection) {
ret = document.getSelection();
} else if (document.selection) {
ret = document.selection.createRange().text;
}
return ret;
}
I don't know where to check to see if it's from a textarea or from somewhere else, and I don't know how to change a specific part of a textarea's text
There are a lot of cross browser nuances when it comes to text selection. There are several jQuery plugins trying to deal with this. I'd recommend using a-tools. I've used it in the past, and it works as advertised.
This might help you :
Finding selection start and end position in a textarea
Also i just tested this and it works (it returns the selected text , so you can modify it and assign the value back to the textarea
Ref : http://www.codingforums.com/showpost.php?p=235174&postcount=5
<script type="text/javascript">
<!--//
function selectedText(input){
if(document.selection && document.selection.createRange().text != ''){ // IS IE
alert(document.selection.createRange().text);
}
else{ // Not IE.. assume Mozilla?
var startPos = input.selectionStart;
var endPos = input.selectionEnd;
alert(input.value.substring(startPos, endPos))
}
}
//-->
</script>
</head>
<body>
<form name="reportForm">
<textarea name="report">this is a test</textarea>
<button onclick="selectedText(this.form.report)">Alert Selection</button>
</form>

Highlighting text problem

I am fixing an editor and I have highlighting text problem.
I got this code for checking what have the user highlighted (more details below the code):
function getSelectionHTML()
{
var iframe = document.getElementById(theEditorID);
var win, doc = iframe.contentDocument;
if(doc)
win = doc.defaultView;
else
{
win = iframe.contentWindow;
doc = win.document;
}
var userSelection;
if(win.getSelection)
{
userSelection = win.getSelection();
if(userSelection.getRangeAt)
var range = userSelection.getRangeAt(0);
else
{
var range = document.createRange();
range.setStart(userSelection.anchorNode, userSelection.anchorOffset);
range.setEnd(userSelection.focusNode, userSelection.focusOffset);
}
var clonedSelection = range.cloneContents();
var div = document.createElement('div');
div.appendChild(clonedSelection);
callIcons(div.innerHTML);
}
else if(doc.selection)
{
userSelection = document.selection.createRange();
callIcons(userSelection.htmlText);
}
};
When the user highlight some bold text and some other italic text i got this output:
<b>some text</b><i>some other text</i>
But when the user highlight only bold text i got this output (there is no 'bold' tag):
some text
You can check that, live, here - http://brownfolder.com/06/
You'll see an alert after highlighting some text.
Do you have any idea how can I fix this?
Thanks in advance.
Browsers vary over whether they include the surrounding tags in the selection. They usually don't include the surrounding tags if the selection is entirely contained within the tags. It's possible to walk up the DOM from the start of the selection and check if each element is a <b> tag. But if the iframe you're working with uses contenteditable, there's no guarantee it will bold with <b> tags. There are other ways the text might be bolded: IE usually adds <STRONG> tags to bold, and Firefox and WebKit may use <span style="font-weight:bold>.
It's probably better to use queryCommandState('bold') on the iframe document instead.

Categories

Resources