Javascript add bold text to a frame - javascript

I want to add bold to the (see illustration). If I do this:
p:function{
sel = this.getSelection().getRangeAt(0);
var caretPosition = sel.endOffset;
var existingText = this.iframe[0].contentWindow.document.body.innerText;
var before = existingText.substring(0, caretPosition);
var after = existingText.substring(caretPosition);
this.iframe[0].contentWindow.document.body.innerHTML= before
+'**<b>**(see illustration)**</b>** ' + after;
},
Then all the text that i write after (see illustration becomes bold).

If you want to create an editable iframe with Bold, Italic or other commands you can use the underlying browser commands which you can fire through the execCommand method.
You could see there resources for more information:
https://developer.mozilla.org/en-US/docs/Web/API/document.execCommand
https://developer.mozilla.org/en/docs/Rich-Text_Editing_in_Mozilla
These method is supported by all modern browsers.

I've provided a simple example that shows you how execCommand works
<iframe id = "my-editable">
<html>
<body contenteditable = "true">
</body>
</html>
</iframe>
JavaScript code:
var iframe = document.getElementById('my-editable');
var iframeDoc = iframe.contentWindow.document;
// type and select some text into iframe
// For making selected text to be bold, just execute the following command
iframeDoc.execCommand('bold');
UPDATE
var body = iframeDoc.body;
body.innerHTML = body.innerHTML + '<b>' + 'your bold text' + '</b>' + 'your boldless text'

Related

Using CEFSharp to edit <textarea>

I am able to edit a regular textbox within an iFrame in CefSharp like so:
Browser1.GetBrowser().GetFrame("iFrame1").ExecuteJavaScriptAsync("document.getElementById('ElementID').value=" + '\'' + "1234" + '\'');
However, because a textarea doesn't have a value:
<iframe id="iFrame1" name="iFrame1">
<textarea name="txtareaname" id="txtareaname1">sometexthere</textarea>
</iframe>
I am unable to execute a similar line of code to edit the text in the textarea:
textarea.Browser1.GetBrowser().GetFrame("iFrame1").ExecuteJavaScriptAsync("document.getElementById('txtareaname1').value=" + '\'' + "1234" + '\'');
I have also tried:
textarea.Browser1.GetBrowser().GetFrame("iFrame1").ExecuteJavaScriptAsync("document.getElementById('txtareaname1').innertext=" + '\'' + "1234" + '\'');
How do I adjust my code to edit this textarea?
OP: However, because a textarea doesn't have a value I am unable to
execute a similar line of code to edit the text in the textarea.
The assumption is wrong, setting value attribute works fine for teaxtarea.
You should just make sure the document, including the iframe has been loaded and you have selected the correct iframe using correct name and then you have selected the correct textarea using correct id.
Example
Here is a minimal complete verifiable example which shows how you can find the iframe and set the value of a textarea inside the iframe.
To make the example independent from externals sources and make verification easier, instead of initializing iframe using its src attribute, I've initialized iframe using script.
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
var content = new HtmlString(#"
<!DOCTYPE html>
<html>
<body>
<iframe id=""iFrame1"" name=""iFrame1"" src=""about:blank""></iframe>
<script>
var doc = document.getElementById('iFrame1').contentWindow.document;
doc.open();
doc.write('<html><head><title></title></head><body>' +
'Address:<br>' +
'<textarea id=""myTextarea"">342 Alvin RoadDucksburg</textarea>' +
'</body></html>');
doc.close();
</script>
</body>
</html>
");
var browser = new ChromiumWebBrowser(content)
{ Dock = DockStyle.None, Size = new Size(400, 200), Location = new Point(8, 42) };
Controls.Add(browser);
var button = new Button() { Text = "Click Me", Location = new Point(8, 8) };
Controls.Add(button);
button.Click += (obj, args) => {
browser.GetBrowser().GetFrame("iFrame1")
.ExecuteJavaScriptAsync("document.getElementById('myTextarea').value=" +
"'Fifth Avenue, New York City'");
};
}

jQuery insert/remove text at specific position in input field/textarea

I am trying to do similar thing as YouTube has when you are embeding a video and you want to get a code. You can click on checkboxes or select size and it dynamically changes the value of input field.
Does somebody have idea how to do it?
I managed to write a code that is replacing the width correctly, but I dont know how to make a code that would add &scheme=XXX at the end of the link or remove it if user selects no color scheme.
This is the code for width,I dont think its best one, but works:
$("#width").on("change keyup", function(){
var width = $(this).val();
if (width){
$("#embed-text").val($("#embed-text").val().replace(/ (width\s*=\s*["'])[0-9]+(["'])/ig, ' width=\''+width+'\''));
}
});
Here is textarea which I am trying to change and inputs I'm using for it:
The ID is taken from PHP, in actual textarea that jQuery sees the ".$id." is actual number
<textarea class='clean' id='embed-text'><iframe src='http://my.url/embed/?r=".$id."' width='600' height='".$height."' frameborder='0' marginwidth='0' marginheight='0' allowtransparency='true'></iframe></textarea>
<div style='padding-right: 10px; display: inline-block;'>
Color scheme:
<select id='schemes' class='clean'>
<option value='-'>None</option>
<option value='xxx'>Xxx</option>
</select>
</div>
<div style='padding-right: 10px; display: inline-block;'>
Width: <input type='number' min='250' max='725' value='600' id='width' class='clean'>
</div>
When user does not select any scheme (or changes from XXX to None), I want link in textarea (iframes src) to be like this:
http://my.url/embed/?r=X
But when he selects any scheme, i would like it to look like this:
http://my.url/embed/?r=X&scheme=XXX
I actually have no idea how to do this. Tried googling for more than hour, but I don't know what the ID will be (to identify position where to add the string), thats PHP value and I cant pass it to external script file, so I tried to find if I can insert something at specific position (ie.: 15th character from start) with JS, but could not find anything.
Thanks.
I separate some functions in order to keep the code clean check this I think that is what you were looking for JsFiddle
var generateUrl = function(id,colorScheme) {
var baseUrl = "http://my.url/embed/?";
var url = baseUrl.concat("r="+id);
if (colorScheme != null && colorScheme != '')
url = url.concat("&scheme="+colorScheme);
return url;
};
var changeUrl = function(id, colorScheme) {
var url = generateUrl(id, colorScheme);
var srcPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(srcPattern),"src='"+url+"'");
$("#embed-text").val(newEmbedText);
};
var changeWidth = function(newWidth) {
var widthPattern = "width='([0-9]*)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(widthPattern),"width='"+newWidth+"'");
$("#embed-text").val(newEmbedText);
};
var getURLParameter = function(url,parameterName) {
return decodeURIComponent((new RegExp('[?|&]' + parameterName + '=' + '([^&;]+?)(&|#|;|$)').exec(url)||[,""])[1].replace(/\+/g, '%20'))||null
};
var getId = function() {
var urlPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var url = embedText.match(new RegExp(urlPattern))[1];
var id = getURLParameter(url, 'r');
return id;
};
$("#width").on("change keyup", function(){
var width = $(this).val();
var colorScheme = $(schemes).val();
changeWidth(width);
changeUrl(getId(),colorScheme);
});
And i removed the value '-' for the first option just leave it in blank.

Trying to write to iframe on keyup

I am trying to write to my iframe on keyup but it does not update. I will run through the code I am using to try to achieve this.
First, I am grabbing the original HTML that I would like on the iframe (through AJAX) and writing that to the iframe as so:
var base_tpl = base_html; //get base template html.
var iframe = document.querySelector('#output iframe'),
iframe_doc = iframe.contentDocument;
iframe_doc.open();
iframe_doc.write(base_tpl);
iframe_doc.close();
After that I am attaching document.querySelector to the relevant text areas that will serve as inputs for the changes that I want to show up on the corresponding elements within the iframe. Here is how I am doing that:
var the_title = document.querySelector('#the_title2 textarea'),
the_subheading = document.querySelector('#the_subheading2 textarea'),
the_image_url = document.querySelector('#the_image_url2 textarea'),
the_description = document.querySelector('#the_description2 textarea'),
the_signup_button_text = document.querySelector('#the_signup_button_text2 textarea'),
the_email_capture_text = document.querySelector('#the_email_capture_text2 textarea'),
the_email_capture_button_text = document.querySelector('#the_email_capture_button_text2 textarea');
the_css = document.querySelector('#the_css2 textarea');
var editors = [the_title, the_subheading, the_image_url, the_description, the_signup_button_text, the_email_capture_text, the_email_capture_button_text];
I then attach these to on keyup listeners as such:
// Attaching the onkeyup Event
editors.forEach(function(editor, i, arr) {
editor.addEventListener('keyup', function() {
// The function that'll prepare the code and inject
// into the iframe.
//alert(the_title.value);
render();
}, false);
});
Notice the render function, it works like this:
var render = function() {
var source = prepareSource();
var iframe = document.querySelector('#output iframe'),
iframe_doc = iframe.contentDocument;
console.log(source);
iframe_doc.open();
iframe_doc.write(source);
iframe_doc.close();
};
Prepared source is the function that puts together the newly inputted elements. The methodology behind it can be seen here:
var prepareSource = function() {
var title = the_title.value,
subheading = the_subheading.value,
image_url = the_image_url.value,
description = the_subheading.value,
signup_button_text = the_image_url.value,
email_capture_text = the_subheading.value,
email_capture_button_text = the_image_url.value,
css = the_css.value,
src = '';
src = base_tpl;
// Title
src = src.replace("<div id='the_title'><h3><?php echo $page->title; ?></h3></div>", "<div id='the_title'><h3>" + title + "</h3></div>");
// Subheading
src = src.replace("<div id='the_subheading'><h3><?php echo $page->subheading; ?></h3></div>", "<div id='the_subheading'><h3>" + subheading + "</h3></div>");
// Image URL
src = src.replace("<div id='the_image_url'><h3>", image_url + "</h3></div>");
// Description
src = src.replace("<div id='the_description'><h3>", description + "</h3></div>");
// Signup Button Text
src = src.replace("<div id='the_signup_button_text'><h3>", signup_button_text + "</h3></div>");
// Email Capture Text
src = src.replace("<div id='the_email_capture_text'><h3>", email_capture_text + "</h3></div>");
// Email Capture Button Text
src = src.replace("<div id='the_email_capture_button_text'><h3>", email_capture_button_text + "</h3></div>");
// CSS
css = '<style>' + css + '</style>';
src = src.replace('</head>', css + '</head>');
return src;
};
My question is of whether i am doing something wrong here. The main issue is that the prepared source does not seem to be working at all. Nothing changes on the iframe on keyup. I have tested this with console.log. It does not seem to be affected at all.
I would appreciate any help here.
Cheers!
Tapha.
EDIT: Please ignore the elements after subheading in the 'prepared source' section - i have only done the title and subheading portions for testing purposes.

How to change h:outputText value by JavaScript?

I already tested with 2 inputText, It runs well
for example
var tdate = document.getElementById('txtDate'); //h:inputText
var tdt = document.getElementById('txtDateTime'); //h:inputText
tdate.onchange = function(){
tdt.value = tdate.value;
};
How can I change the value of " tdt " - h:outputText?
var tdate = document.getElementById('txtDate'); //h:inputText
var tdt = document.getElementById('txtDateTime'); //h:outputText
Look in the generated HTML source. Rightclick page in browser and view source. You'll see that the <h:outputText> renders a HTML <span> element with the value in its body. To alter the body of a <span> in JavaScript you need to manipulate the innerHTML.
tdt.innerHTML = "new value";

How can I run this in HTML?

var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');
var theBR = document.createElement('br');
theNewParagraph.setAttribute('title','The test paragraph');
var theText1 = document.createTextNode('This is a sample of some ');
var theText2 = document.createTextNode('HTML you might');
var theText3 = document.createTextNode('have');
var theText4 = document.createTextNode(' in your document');
theBoldBit.appendChild(theText2);
theBoldBit.appendChild(theBR);
theBoldBit.appendChild(theText3);
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
theNewParagraph.appendChild(theText4);
document.getElementById('someElementId').appendChild(theNewParagraph);
Also, can anyone help me by explaining this?
What you have is a snippet of JavaScript code. I've added comments to the code to explain each section:
// Create 3 elements, a <p>, a <b> and a <br>
var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');
var theBR = document.createElement('br');
// Set the title attribute of the <p> element we created
theNewParagraph.setAttribute('title','The test paragraph');
// Create 4 "text nodes", these appear as text when added to elements
var theText1 = document.createTextNode('This is a sample of some ');
var theText2 = document.createTextNode('HTML you might');
var theText3 = document.createTextNode('have');
var theText4 = document.createTextNode(' in your document');
/* Add the second text node, the <br> element and the 3rd text node to the
<b> element we created */
theBoldBit.appendChild(theText2);
theBoldBit.appendChild(theBR);
theBoldBit.appendChild(theText3);
/* Add the first text node, the <b> element and the 4th text node to the
<p> element we created. All nodes are now descendants of the <p> */
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
theNewParagraph.appendChild(theText4);
/* Finally, add the <p> element to an element with an id attribute of
someElementId, so we can see all the content on our page */
document.getElementById('someElementId').appendChild(theNewParagraph);
The result is the following HTML as the content of someElementId:
<p title="The test paragraph">This is a sample of some <b>HTML you might<br>
have</b> in your document</p>
Others have explained how to add this script to your document using the <script> element.
Put the above in a <script type="text/javascript"> at the bottom of your page and make sure there's an <div id="someElementId"> in your document.
What it's doing is creating a new <p>, <b> and <br> tag. It then sets the title on the paragraph, adds some text to all tags and finally adds the whole mess to an element with id #someElementId.
You can see it in action here.
Here is a suitable test harness. Paste the following into a new .html file:
<html><head><script language="javascript"><!--// your javascript here:
function _onload()
{
var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');
var theBR = document.createElement('br');
theNewParagraph.setAttribute('title','The test paragraph');
var theText1 = document.createTextNode('This is a sample of some ');
var theText2 = document.createTextNode('HTML you might');
var theText3 = document.createTextNode('have');
var theText4 = document.createTextNode(' in your document');
theBoldBit.appendChild(theText2);
theBoldBit.appendChild(theBR);
theBoldBit.appendChild(theText3);
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
theNewParagraph.appendChild(theText4);
document.getElementById('someElementId').appendChild(theNewParagraph);
}
//--></script></head><body onload='_onload()' id='someElementId'></body></html>
How to run:
<head>
<script type="text/javascript">
function CreateTestParagraph () {
var theNewParagraph = document.createElement('p');
var theBoldBit = document.createElement('b');
var theBR = document.createElement('br');
theNewParagraph.setAttribute('title','The test paragraph');
var theText1 = document.createTextNode('This is a sample of some ');
var theText2 = document.createTextNode('HTML you might');
var theText3 = document.createTextNode('have');
var theText4 = document.createTextNode(' in your document');
theBoldBit.appendChild(theText2);
theBoldBit.appendChild(theBR);
theBoldBit.appendChild(theText3);
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
theNewParagraph.appendChild(theText4);
document.getElementById('someElementId').appendChild(theNewParagraph);
}
</script>
</head>
<body onload="CreateTestParagraph ()">
<div id="someElementId"></div>
</body>
Your CreateTestParagraph method creates the following HTML content dynamically:
<p title="The test paragraph">This is a sample of some <b>HTML you might<br>have</b> in your document</p>
and put that contents into the someElementId element.
Related links:
createElement method,
createTextNode method,
appendChild method,
getElementById method,
onload event

Categories