Jquery get and set css attribute of some part of html string - javascript

I'm writing an html editor control.
I want to change css attributes of selected text of the content.
I get the selectedcontent by window.getSelection();
What is the best way to make bold selected text, and to understand selected text is bold then to make it normal.
Replace with required tags doesn't work. Since similar texts can be in content.
It looks quite complicated to me.
I'm looking for the best practise to do it.

Try this sample snippet
You can make bold as selected text via "document.execCommand('bold');"
Html
<div contenteditable="true" class="textEditor">Text1.
Text2.
Text3.
Text4.
Hi, this is text of some kind
Lorem ipsum...
</div>
Jquery
Catch selection change event by jquery-selectionchange event.
Make bold and normal by document.execCommand('bold');
$(document).on('selectionchange', function(e) {
document.execCommand('bold');
});
JsFIddle:
http://jsfiddle.net/XCb95/132/

Related

How can a DIV act like another element in Javascript?

My skills in Javascript are limited and for practicing i'm trying to programatically fill some elements using JS code, using Chrome's Developer Tools. I navigate to a site, access the console and try to manipulate DOM elements using JS code.
Usually elements a user can input data are INPUT, TEXTAREA , SELECT and so on. But latelly i've been seeing elements that are user-editable, but are simply DIVs. In other words, a DIV acting like an INPUT or TEXTAREA, and this got me confused.
Here is an example : i extracted this source from a page to post topics in a Facebook Group.
Note that the div that has the 'Write something' innerhtml works as a textarea in the page. You can reproduce this code in any Facebook Group, ie https://www.facebook.com/groups/914737511952904/ (you might need to join the group before see the box to post a topic).
<div class="_1mwp _1mwq _5bu_ _5yk1"><div class="_5yk2" tabindex="-2">
<div class="_5rp7">
<div class="_1p1t">
<div class="_1p1v" id="placeholder- 2bc29">Write something... </div>
</div>
</div>
</div>
If this element was a TEXTAREA, i could easily do something like
document.getElementById('elementId').value = 'New text';
But the 'textarea' element in the above case is actually a DIV and nothing else.
How can i insert text on it using JS ? An how can a DIV act like a textarea or an input ?
Thanks !
How can I insert text on it using JS?
That's quite simple. Just use the innerHTML property to assign the text value.
document.getElementById('elementId').innerHTML = "Text inserted"
However you can do the same using just CSS, and then retrieving the text from the div invoking the same property.
How can a DIV act like a textarea or an input?
A very practical way is using the contentEditable property over the div, but you can use CSS styles as well, and in some cases with some JavaScript code.
You have a simple example here using CSS styles and contentEditable property:
https://jsfiddle.net/ThinkingStiff/AbKTQ/
How can I insert text on it using JS?
element.textContent = "text content"
SNIPPET 1
var div = document.querySelector('div');
div.textContent = "line of text by textContent"
<div></div>
An how can a DIV act like a textarea or an input?
You can add contneteditable to an element that's not originally editable.
<div contenteditable></div>
See Snippet on how to set contenteditable by JS
SNIPPET 2
var editor = document.querySelector('div');
editor.setAttribute('contenteditable', true);
<div>This is a div. Click on me and start typing.</div>

HTML + JS: Best way to style up textarea's content

What is the best way to style up content in the HTML textarea element. My goal is to have parts of text in my textarea red (for example), so I would do <span style="color: red">My text part</span> but this way the textarea shows everything including my HTML code <span> ... </span> as its value.
Next thing I tried is to overlay div with my textarea in which would be my desired code width <span> ... </span> code shown correctly with red styled text and without HTML code. User will edit textarea's value which would be processed and shown in my div. But this method seems to me too dirty. What is your advises?
Styling text inside a textarea is not possible, you can check this. You could use a plugin like TinyMCE, which will show a text editor in the place of your textarea, and there you can put the style that you want to the text.

update text on a textarea as user types, based on the syntax?

For example I have a textarea and I'm typing this:
<b>Bolded</b> and <i>italic</i> and <b><i>bold+italic</i></b>
as I am typing this to my textarea, the text will become bolded or italic like this:
Bolded and italic and bold+italic
Note that it does not have to be <b> or <i>, it could be **text** and it becomes text, I have no problem on creating the custom syntax, I just need to know if it is possible to update it live in js or jquery?
I was thinking of using (this is in CoffeeScript):
$('div#mdEditor').on 'change', ->
# but no idea how to continue?
UPDATE
It does not have to be textarea though, I am using a contenteditable div so I can parse it on live if needed, again, I have no idea how.
Source: http://jakiestfu.github.io/Medium.js/docs/
Goal: When we paste content in editor allow only <p>, <b>, <a>, and <i> tags only

html, css, javascript with textarea

I need to make a text editor for my site. Here are a few questions that I have:
How can I retrieve the row selected in the text area using JavaScript?
How can I style the first line of the text without styling all rows the same?
Here is an example of what I need:
<textarea>
<span class='center_align'>Hello world</span>
<span class='left_align'>This is a nice paragraph aligned to the left.</span>
</textarea>
I know <textarea> reads HTML into its input, but how would I go about to style this?
Sounds like you need a Rich Text Editor: try TinyMCE (as used by WordPress): http://www.tinymce.com/

jQuery appended text is invisible

I'm trying to create a couple of buttons above a textarea to insert some HTML code -- a VERY poor-man's HTML editor. I have a couple of INPUT elements, and I'm using jQuery to set a click handler that will call's jQuery's append() or html() or text() functions.
The handler fires, it shows a debug alert(), but the text I'm trying to append doesn't show up in the textarea. When I inspect the textarea in Firebug, I see the text I'm appending as a child of the textarea -- but it's dimmed, as when an element's style is set to display:none. But Firebug's CSS inspector doesn't show any change to the display or visibility properties.
When I set the click handler to 'append()', and then click multiple times, in Firebug I see the text being added over and over again -- but each new chunk is still invisible. If I choose 'Edit HTML' in Firebug and then type some chars next to the appended text, the entire text block -- the text added by jQuery and the stuff I added in Firebug -- suddenly appear.
This also happens if I don't use a click handler, but call my append function using an inline handler like onclick="javascript:insert('bold');"
Anyone have any idea why the appended text is not displayed?
Here's the relevant code:
The HTML:
<input type='button' id='bold' value='B' onclick='javascript:insert("bold")' />
<textarea name='PersonalGreeting' id='PersonalGreeting'>default text</textarea>
The Javascript:
function insert( cmd ) {
switch ( cmd ) {
case 'bold':
$('#PersonalGreeting').append('<b>bold text here</b>');
break;
}
}
I would guess that jQuery is trying to append HTML DOM elements to the textarea.
Try using the val method to get and set the textarea's value, like this:
$('#PersonalGreeting').val($('#PersonalGreeting').val() + '<b>bold text here</b>');
The basic problem is that you can't put HTML inside a <textarea>. In fact, you can't append HTML elements to one at all. You could use the .val() method to change the text shown inside, but that won't make it bold. That will just make it have <b> showing as part of the text.
An off-the-shelf WYSIWYG editor like TinyMCE is free and easy to implement. Rather than reinvent the wheel (which is a lot harder than it might look), try an existing wheel out.
SLaks and VoteyDisciple are correct. You're usage of append is faulty as you are perceiving it as a string function.
From http://docs.jquery.com/Manipulation/append
Append content to the inside of every
matched element. This operation is the
best way to insert elements inside, at
the end, of all matched elements. It
is similar to doing an appendChild to
all the specified elements, adding
them into the document.
Reinventing the wheel on this one is likely more headache than its worth unless this is an attempt to create a superior, competing product or for your own experimentation.
Also, I would shy away from use of obtrusive JavaScript as you have shown in your example with onclick='javascript:insert("bold")' embedded in the input element. Instead, you'll have a more elegant solution with something like the following:
HTML
<input type="button" value="B" class="editor-command" >
<input type="button" value="I" class="editor-command" >
<input type="button" value="U" class="editor-command" >
JavaScript (not tested)
$(document).ready(function() {
var textarea = $('#PersonalGreeting')
$(".editor-command").each(function(i, node) {
textarea.val(textarea.val() + '<$>text here</$>'.replace(/\$/g, node.value);
});
});
If the main issue is the textarea not being visible, I would try this:
$('#PersonalGreeting').append('<b>bold text here</b>').show();
Might be worth a shot.
edit: In the vain of not trying to reinvent the wheel, I've had success with WYMEditor
You could do this:
$('#PersonalGreeting').append('[b]bold text here[/b]');
But that won't actually render the text as bold. To be honest I'm not actually sure how to render text as bold inside a textarea, I imainge some js trickery.

Categories