Applying css to a javascript variable - javascript

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;
}

Related

How can I change the background color of element in an array

I have an array of 5 divs
`<div id="cap-left2"</div>`
`<div id="cap-left1"</div>`
`<div id="cap-base"</div>`
`<div id="cap-right1"></div>`
`<div id="cap-right2"</div>`
all these divs have a background .
In my javascript I have :
let items = [capBase,capLeft1,capLeft2,capRight1,capRight2];
this works :
`var tom = items[Math.floor(Math.random()*items.length)]
console.log(tom)`
and this works
`var tom = items[Math.floor(Math.random()*items.length)]`
`console.log(tom.style)`
but I want the backgroundColor and neither of these work:
`var tom = items[Math.floor(Math.random()*items.length)]`
`console.log(tom.style.background)`
`var tom = items[Math.floor(Math.random()*items.length)]`
`console.log(tom.style.backgroundColor)`
what I am trying to do is lets say i have 5 swatches represented by 5 elements in an array . i want to be able to have a button that allows me to randomize what colors fill each element
any help would be appreciated
element.style represent style of the element, it will only be populated if style attribute is present (aka in-line style), CSS style will not affect that object.
So, element.style.backgroundColor will be empty, unless element has style="background-color: red;" as an attribute.
If you need get actual rendered style of an element, use
window.getComputedStyle(element).backgroundColor
document.querySelectorAll("div").forEach( div =>
{
console.log("style: " + div.style.backgroundColor, "final: " + window.getComputedStyle(div).backgroundColor, div);
});
body > div[id]
{
width: 1em;
height: 1em;
background-color: green;
border: 1px solid black;
}
<div id="cap-left2"></div>
<div id="cap-left1" style="background-color: red;"></div>
<div id="cap-base"></div>
<div id="cap-right1"></div>
<div id="cap-right2"></div>
const xx = window.getComputedStyle(searchBtn).getPropertyValue('background-color')
console.log(xx)
you can access only inline css proprty values via styleproperty. You need getComputedStyle

JavaScript's document.write doesn't work like PHP's echo

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");

Javascript to dynamically add textbox , and again convert the text box to text

I need something like a fill in the blanks sheet for children. When people click the ------ (dashes) it should turn into a textbox, and people can type it. after that when they move from that element after typing, it should turn into the text that they entered inside that text box.
I really dono how to approach this problem. I tried the following code, but what happens is, i am unable to type inside the text box. The cursor is not appearing at all
<html>
<head>
<title>NSP Automation</title>
<script src ="jquery.min.js">
</script>
</head>
<body>
<div class="container">
My Name is = <span id="name">__________<span>
</div>
<script>
$(document).on('click', '#name', function(){
document.getElementById("name").innerHTML = "<input type=\"text\">";
});
</script>
</body>
</html>
any pointers on how to achieve this ?
Thanks,
Since you've set the listener on the whole document, you will be recreating the input-tag with every click. Try something like:
$('#name').on('click', function(){
this.innerHTML = "<input type=\"text\">";
$('#name').off('click')
}
After clicking on the span-element, you remove the listener on it again, and you should be able to type.
http://jsfiddle.net/218rff9v/
Here is an example that generates the wished behaviour for all spans in your container. Some details can be improved but I think it's working as expected.
function convertSpanToInput() {
// Insert input after span
$('<input id="tmp_input">').insertAfter($(this));
$(this).hide(); // Hide span
$(this).next().focus();
$("#tmp_input").blur(function() {
// Set input value as span content
// when focus of input is lost.
// Also delete the input.
var value = $(this).val();
$(this).prev().show();
$(this).prev().html(value);
$(this).remove();
});
}
$(function() {
// Init all spans with a placeholder.
$(".container span").html("__________");
// Create click handler
$(".container span").click(convertSpanToInput);
});
Here is an html example with which you can test it:
<div class="container">
My Name is = <span></span>. I'm <span></span> years old.
</div>
JsFiddle: http://jsfiddle.net/4dyjaax9/
I'd suggest you have input boxes and don't do any converting
Simply use CSS to remove the borders and add a dashed border bottom
input[type=text]{
border:none;
border-bottom:1px dashed #777;
} <!-- something like that -->
add a click handler to add a edited class, so you can remove the bottom border
input[type=text].edited{
border:none;
}
That way you don't need to replace html elements, you just style them to look different
Why not use text input and only change CSS classes?
CSS:
.blurred{
border-style: none none solid none;
border-width: 0px 0px 1px 0px;
border-bottom-color: #000000;
padding: 0px;
}
.focused{
border: 1px solid #999999;
padding: 3px;
}
JavaScript:
$('#nameInput').focus(function(){
$(this).removeClass('blurred').addClass('focused');
});
$('#nameInput').blur(function(){
$(this).removeClass('focused').addClass('blurred');
});
HTML:
<div class="container">
My Name is = <span id="name"> <input id="nameInput" type="text" class="blurred"></input> <span>
</div>
Check this jsfiddle:
http://jsfiddle.net/gwrfwmw0/
http://jsfiddle.net/we6epdaL/2/
$(document).on('click', '#name', function(e){
if( $("#myText").is(e.target))
return;
$(this).html("<input type='text' id='myText' value='"+ $(this).html() +"'>");
});
$(document).on("blur", "#name", function(){
$(this).html( $("#myText").val() );
});

Change text input border color

I want to make a form where data is verified using JavaScript before being sent.
When a field is empty, I want to set its border to red.
HTML code:
<label>Question: </label><input type = "text" maxlength = "100" name = "question"> <br />
JavaScript code 1:
fields[i].style.borderColor = "red";
JavaScript code 2:
fields[i].style.border = "1px solid red";
If I use JS code 1, the border changes its color but it has the width bigger than before (even though I do not say anything about border width).
If I use JS code 2, the text input shrinks with 2px and the change is noticeable.
What should I do to change only the border color?
Actually this is preferred by adding and removing classes:
$("input").change(function()
{
var value = $(this).val();
if(value=="")
{
$(this).addClass("red-border");
$(this).focus();
}else
{
$(this).removeClass("red-border");
}
});
And your CSS:
.red-border{
border: 1px solid red;
}
The default user agent stylesheet uses this for the input field:
border: 2px inset;
Now you may ask why is this not defined by default?
by default(In IE the appreance is hard-coded):
appearance: textfield;
But whenever you change something:
appearance: none;
And when the appearance is none, you will see the 2px inset border.
So actually the width is the problem here:
So you want to change 2 propeties: Border-width and border-color
You would need 2 lines now:
document.getElementsByTagName('input')[0].style.border = "red";
document.getElementsByTagName('input')[0].style.borderWidth = "1px";
jsFiddle
However your own solution might be elegant, as it is defined with one line of code:
fields[i].style.border = "1px solid red";
Note that the inset style sets the top and right border lighter where the bottom and left border is the given color. Setting the style to solid will solve this.
It won't harm your code to use the whole shorthand property of border. You always have to be very specific when you want to win the battle with the user agent stylesheet.
I have something like this in production, only it uses alerts instead of color change. Use CSS Styles & classes:
CSS
.error {
border:2px solid red;
}
JavaScript
<script>
function checkField(){
var f = document.getElementById('<name of field>').value;
if (f === "") {
document.getElementById('<name of field>').className = document.getElementById('<name of field>').className + " error";
return false;
}
}
</script>
Then add this to your button/control's click event:
return checkField()
This SO post seems to be similar:changing textbox border colour using javascript
Use outline instead of border.
fields[i].style.outline = "1px solid red";
Try this out. Jquery
$("input").change(function ()
{
var value = this.value;
if(value=="")
{
$(this).css("border", "1px solid red");
}else
{
$(this).css("border",'');
}
}).trigger("change");
Html
<input type="text" class="col">

If textbox contain a specific string do some function - javascript

I am wondering how to search specific string in big textbox (which contains 200 words) so I can make function to color them. Ex. In textbox there is a sentence "my dog is happy" and i want string "dog" to become red by button or sth else. Is it possible???
Yes, it is possible. But don't use a text box or text area, use a div with contenteditable = "true":
<div id="editableDiv" class="editable" contenteditable="true">
This is a sentence containing 'dog'.<br />
You can edit the contents of this div.
</div>
<button id="highlightBtn">Highlight "dog"</button>
<script type="text/javascript">
highlightBtn.onclick = function() {
var elem = document.getElementById('editableDiv');
elem.innerHTML = elem.innerHTML.replace(/dog/g,
'<span class="redText">dog</span>');
}
</script>
And don't forget to create the classes redText and editable in your stylesheet:
.editable {
padding: 5px;
border: dashed 1px black;
}
.redText {
color: red;
}
JSFiddle: http://jsfiddle.net/ProgramFOX/UMMPh/

Categories

Resources