I'm trying to get JavaScript's document.write to work like PHP's echo. For example:
<?php
echo "
<style>
div {
border: 1px solid black;
}
<style>
";
?>
<div> Hello </div>
would work just fine in PHP, and it'll make a border of 1px solid black around the div. However in JavaScript:
<script>
document.write("
<style>
div {
border: 1px solid red;
}
<style>
");
</script>
<div> Hello </div>
it wouldn't work, and it doesn't make a border of 1px solid black around the div. I'm wondering if it's even possible to do the same thing with JavaScript, and if so what am I doing wrong and how to fix it.
I see two errors in your javascript code. The first, You can't use new lines in your code. It needs to be all over one line or concatenated by ending the string then using a + on the next line.
You also aren't closing your style tag, which was disrupting the final output.
The following code works for me:
<script type="text/javascript">
document.write("<style>div {border: 1px solid red;}</style>");
</script>
<div> Hello </div>
Or, as mentioned above with the string concatenation:
<script>
document.write(
"<style>"
+"div {"
+"border: 1px solid red;"
+"}"
+"</style>"
);
</script>
<div> Hello </div>
Just create the styleless div like this:
<div id="box1"></div>
And then you can manipulate the styling with js like this:
document.getElementById('box1').style.cssText = 'background-color:black;height:50px;';
With jQuery, it's even easier:
HTML:
<div id="box1"></div>
jQuery:
$("#box1").css("background-color", "black");
Related
I want to add color and border to a javascript variable using css. Below is my code;
var msg = "OK"; //i want this to colored and bordered with green.
msg = "Conflict"; // i want this to be colored and bordered with red.
I tried another answer from other questions but it doesn't seem to work with me.
If you're just trying to add styles to a JavaScript variable you can't do that, and I don't understand what you would hope to achieve by doing that.
I am therefore going to assume you want to add styles to an html element that you have extracted as a JavaScript variable like so
let msgElement = document.getElementById('msg')
let msg = "OK"
msgElement.innerHTML = msg
In this case, you can add styles to the element like so
msgElement.style.color = "red"
msgElement.style.border = "2px solid red"
In your example, when you change the value of msg to "Conflict", you are doing just that - changing it. You can't have two separate values held by the same variable.
As one of the comments says, this is basic web development, so I would advise some further reading, or an online course such as those provided by Codeacademy
As the other answers state, you can't apply a CSS rule to a variable. You can, however, do something like this:
<html>
<head>
<style>
.redgreen {border-style: solid; border-color: green; color: red;}
</style>
<script>
function foo() {
let msg = "<div class='redgreen'>Hello, world!</div>";
document.getElementById("themsg").innerHTML = msg;
}
</script>
</head>
<body onload='foo();'>
<p id='themsg'>Your message here</p>
</body>
</html>
That is, define "msg" as an HTML element instead of a text string.
You can't add CSS to a javascript variable.
if you are create element using javascript
html:
<div class="parent-div">
</div>
js:
var msg = "OK";
element = document.createElement('p');
// Give the new element some content and css
element.innerHTML = msg;
element.style.color = 'green';
element.style.border = "1px solid red";
// append element to parent div
document.querySelector('.parent-div').appendChild(element);
Just do without javascript
html:
<div class="parent-div">
<p class="child-one">OK</p>
<p class="child-two">Conflict</p>
</div>
css:
.parent-div .child-one {
color: red;
border: 1px solid green;
}
.parent-div .child-two {
color: green;
border: 1px solid red;
}
I need to be able to render some HTML tags inside a textarea (namely <strong>, <i>, <u>, <a>) but textareas only interpret their content as text. Is there an easy way of doing it without relying on external libraries/plugins (I'm using jQuery)?
If not, do you know of any jQuery plugin I could use to do this?
This is not possible to do with a textarea. You are looking for a content editable div, which is very easily done:
<div contenteditable="true"></div>
jsFiddle
div.editable {
width: 300px;
height: 200px;
border: 1px solid #ccc;
padding: 5px;
}
strong {
font-weight: bold;
}
<div contenteditable="true">This is the first line.<br>
See, how the text fits here, also if<br>there is a <strong>linebreak</strong> at the end?
<br>It works nicely.
<br>
<br><span style="color: lightgreen">Great</span>.
</div>
With an editable div you can use the method document.execCommand (more details) to easily provide the support for the tags you specified and for some other functionality...
#text {
width: 500px;
min-height: 100px;
border: 2px solid;
}
<div id="text" contenteditable="true"></div>
<button onclick="document.execCommand('bold');">toggle bold</button>
<button onclick="document.execCommand('italic');">toggle italic</button>
<button onclick="document.execCommand('underline');">toggle underline</button>
Since you only said render, yes you can. You could do something along the lines of this:
function render(){
var inp = document.getElementById("box");
var data = `
<svg xmlns="http://www.w3.org/2000/svg" width="${inp.offsetWidth}" height="${inp.offsetHeight}">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml"
style="font-family:monospace;font-style: normal; font-variant: normal; font-size:13.3px;padding:2px;;">
${inp.value} <i style="color:red">cant touch this</i>
</div>
</foreignObject>
</svg>`;
var blob = new Blob( [data], {type:'image/svg+xml'} );
var url=URL.createObjectURL(blob);
inp.style.backgroundImage="url("+URL.createObjectURL(blob)+")";
}
onload=function(){
render();
ro = new ResizeObserver(render);
ro.observe(document.getElementById("box"));
}
#box{
color:transparent;
caret-color: black;
font-style: normal;/*must be same as in the svg for caret to align*/
font-variant: normal;
font-size:13.3px;
padding:2px;
font-family:monospace;
}
<textarea id="box" oninput="render()">you can edit me!</textarea>
This makes it so that a textarea will render html!
Besides the flashing when resizing, inability to directly use classes and having to make sure that the div in the svg has the same format as the textarea for the caret to align correctly, it's works!
Try this example:
function toggleRed() {
var text = $('.editable').text();
$('.editable').html('<p style="color:red">' + text + '</p>');
}
function toggleItalic() {
var text = $('.editable').text();
$('.editable').html("<i>" + text + "</i>");
}
$('.bold').click(function() {
toggleRed();
});
$('.italic').click(function() {
toggleItalic();
});
.editable {
width: 300px;
height: 200px;
border: 1px solid #ccc;
padding: 5px;
resize: both;
overflow: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="editable" contenteditable="true"></div>
<button class="bold">toggle red</button>
<button class="italic">toggle italic</button>
An addendum to this: You can use character entities (such as changing <div> to <div>) and it will render in the textarea.
But when it is saved, the value of the textarea is the text as rendered. So you don't need to de-encode. I just tested this across browsers (Internet Explorer back to version 11).
I have the same problem but in reverse, and the following solution. I want to put html from a div in a textarea (so I can edit some reactions on my website; I want to have the textarea in the same location.)
To put the content of this div in a textarea I use:
var content = $('#msg500').text();
$('#msg500').wrapInner('<textarea>' + content + '</textarea>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="msg500">here some <strong>html</strong> <i>tags</i>.</div>
This is possible with <textarea>.
You only need to use the Summernote WYSIWYG editor.
It interprets HTML tags inside a textarea (namely <strong>, <i>, <u>, and <a>).
I have the following jQuery snippet which should replace a code such as [Button] Text Here [/Button] into something like:
<a class="button">Text Here</a>
The javascript I have is the following:
$(document).ready(function() {
var buttonStart = $("body").html().replace(/\[Button\]*/ig,'<a class="button">');
$("body").html(buttonStart);
var buttonEnd = $("body").html().replace(/\[\/Button\]*/ig,'</a>');
$("body").html(buttonEnd);
});
The problem I am having is that it keeps replacing other elements on my page which have nothing to do with the Tags [Button] [/Button]. For insance the following:
<div id="MiddleBarLeft"></div>
Also gets replaced into
<a class="button"><div id="MiddleBarLeft"></div></a>
Shouldn't the Regex I have above just look for [Button] and [/Button] Tags?
Also, is there any other efficient way to go about this?
Thanks
=====================
Update.. this is my entire HTML file which replaces elements that have nothing to do with what I want to replace
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {
var buttonStart = $("body").html().replace(/\[Button\]/ig,'<a class="button">');
$("body").html(buttonStart);
var buttonEnd = $("body").html().replace(/\[\/Button\]/ig,'</a>');
$("body").html(buttonEnd);
});
</script>
<style>
li{
list-style:none;
padding-top:10px;
padding-bottom:10px;}
.button, .button:visited {
background: #222 url(overlay.png) repeat-x;
display: inline-block;
padding: 5px 10px 6px;
color: #fff;
text-decoration: none;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
-moz-box-shadow: 0 1px 3px rgba(0,0,0,0.6);
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.6);
text-shadow: 0 -1px 1px rgba(0,0,0,0.25);
border-bottom: 1px solid rgba(0,0,0,0.25);
position: relative;
cursor: pointer
}
</style>
</head>
<body>
<div>
<ul>
<li>[Button]Test[/Button]</li>
<li></li>
<li>Sample Text</li>
</ul>
</div>
</body>
</html>
The problem stems from the way the replacement occurs - please consider the following fiddle:
http://jsfiddle.net/GYrYa/
As you can see there are two buttons in the end, even though there's only one [Button][/Button] statement - it's because first you're replacing [Button] with <a class='button'> which creates an unmatched tag. This causes an </a> to be added at the end. Then you're replacing [/Button] with </a>, which creates another unmatched tag - this time <a>, at the end.
A better solution would be this:
http://jsfiddle.net/GYrYa/1/
EDIT: http://jsfiddle.net/GYrYa/2/ to omit script tag matching
EDIT 2: http://jsfiddle.net/GYrYa/5/ - final solution, incorporating #Rain Diao non-greedy matching
EDIT 3: Added performance test cases: http://jsperf.com/eithed-rsc3, please read the discussion below #Rain Diao's answer for the genesis of it
In actually, I did a quick testing, but cannot reproduce your problem. Please offer me more details, like an example.
two tips, ccouldimprove the performance:
remove the star in your RegExp. I think it was unneccessary.
call $('body').html(buttonReplaced) only once:
var buttonReplaced = $("body").html()
.replace(/\[Button\]/ig,'<a class="button">')
.replace(/\[\/Button\]/ig,'</a>');
$('body').html(buttonReplaced);
another solution:
var buttonReplaced= $('body').html().replace(/\[Button\](.*?)\[\/Button\]/gi, '<a class="button">$1</a>');
$('body').html(buttonReplaced);
I thinks this code $("body").html(buttonEnd); will replace buttonStart. Mybe you shout try append() method, like this: $("body").append(buttonEnd);
Use + instead of a star in your regex. As the first will match nothing as well
$(document).ready(function() {
var buttonStart = $("body").html().replace(/\[Button\]/ig,'<a class="button">');
$("body").html(buttonStart);
var buttonEnd = $("body").html().replace(/\[\/Button\]/ig,'</a>');
$("body").html(buttonEnd);
});
All,
I am working on populating a div tag with text.
var centName;
centName=centName+$(this).attr('data-centerName');//tried <br/> / '\n'
$("#selOccs").text(centName.Trim(';'));
My div tag is like
<div ID="selOccs" NAME="selOccs" style="width: 350px; height: 100px;border:1px solid ;
overflow-y: scroll; scrollbar-arrow-color: blue; scrollbar-face-color: #e7e7e7; scrollbar-3dlight-color: #a0a0a0; scrollbar-darkshadow-color: #888888">
</div>
The issue is adding line breaks. I need display the centName with line breaks.so far all the values are coming in one line[ as per the code].
I tried adding <--br/--> and '\n' but itseems to be not working..
Use .html() instead of text and in the string you can then use <br/>
var centName;
centName = centName + $(this).attr('data-centerName') + '<br/>';
$("#selOccs").html(centName.Trim(';'));
I need to be able to render some HTML tags inside a textarea (namely <strong>, <i>, <u>, <a>) but textareas only interpret their content as text. Is there an easy way of doing it without relying on external libraries/plugins (I'm using jQuery)?
If not, do you know of any jQuery plugin I could use to do this?
This is not possible to do with a textarea. You are looking for a content editable div, which is very easily done:
<div contenteditable="true"></div>
jsFiddle
div.editable {
width: 300px;
height: 200px;
border: 1px solid #ccc;
padding: 5px;
}
strong {
font-weight: bold;
}
<div contenteditable="true">This is the first line.<br>
See, how the text fits here, also if<br>there is a <strong>linebreak</strong> at the end?
<br>It works nicely.
<br>
<br><span style="color: lightgreen">Great</span>.
</div>
With an editable div you can use the method document.execCommand (more details) to easily provide the support for the tags you specified and for some other functionality...
#text {
width: 500px;
min-height: 100px;
border: 2px solid;
}
<div id="text" contenteditable="true"></div>
<button onclick="document.execCommand('bold');">toggle bold</button>
<button onclick="document.execCommand('italic');">toggle italic</button>
<button onclick="document.execCommand('underline');">toggle underline</button>
Since you only said render, yes you can. You could do something along the lines of this:
function render(){
var inp = document.getElementById("box");
var data = `
<svg xmlns="http://www.w3.org/2000/svg" width="${inp.offsetWidth}" height="${inp.offsetHeight}">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml"
style="font-family:monospace;font-style: normal; font-variant: normal; font-size:13.3px;padding:2px;;">
${inp.value} <i style="color:red">cant touch this</i>
</div>
</foreignObject>
</svg>`;
var blob = new Blob( [data], {type:'image/svg+xml'} );
var url=URL.createObjectURL(blob);
inp.style.backgroundImage="url("+URL.createObjectURL(blob)+")";
}
onload=function(){
render();
ro = new ResizeObserver(render);
ro.observe(document.getElementById("box"));
}
#box{
color:transparent;
caret-color: black;
font-style: normal;/*must be same as in the svg for caret to align*/
font-variant: normal;
font-size:13.3px;
padding:2px;
font-family:monospace;
}
<textarea id="box" oninput="render()">you can edit me!</textarea>
This makes it so that a textarea will render html!
Besides the flashing when resizing, inability to directly use classes and having to make sure that the div in the svg has the same format as the textarea for the caret to align correctly, it's works!
Try this example:
function toggleRed() {
var text = $('.editable').text();
$('.editable').html('<p style="color:red">' + text + '</p>');
}
function toggleItalic() {
var text = $('.editable').text();
$('.editable').html("<i>" + text + "</i>");
}
$('.bold').click(function() {
toggleRed();
});
$('.italic').click(function() {
toggleItalic();
});
.editable {
width: 300px;
height: 200px;
border: 1px solid #ccc;
padding: 5px;
resize: both;
overflow: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="editable" contenteditable="true"></div>
<button class="bold">toggle red</button>
<button class="italic">toggle italic</button>
An addendum to this: You can use character entities (such as changing <div> to <div>) and it will render in the textarea.
But when it is saved, the value of the textarea is the text as rendered. So you don't need to de-encode. I just tested this across browsers (Internet Explorer back to version 11).
I have the same problem but in reverse, and the following solution. I want to put html from a div in a textarea (so I can edit some reactions on my website; I want to have the textarea in the same location.)
To put the content of this div in a textarea I use:
var content = $('#msg500').text();
$('#msg500').wrapInner('<textarea>' + content + '</textarea>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="msg500">here some <strong>html</strong> <i>tags</i>.</div>
This is possible with <textarea>.
You only need to use the Summernote WYSIWYG editor.
It interprets HTML tags inside a textarea (namely <strong>, <i>, <u>, and <a>).