How to edit text style with Javascript - javascript

I'm trying to make a button create new entries in a list that display similar to this:
"#1 new Click Me"
Except I want to make "Click Me" to show up as yellow text in a black box, and then I want to make the black box disappear and the text turn brown on mouseover. I've been able to make the list appear, but don't know how to edit the style of the text to make it appear the way I want to. The most code I think I need to give for this is this:
var li = document.createElement("li");
var liBody = document.createTextNode("#"+numOfNewCMs+
" new " + newClickMe);
li.appendChild(liBody);
And then I insert li into the list.
I figure I should make newClickMe a variable and edit that and then put it next to the rest of the text in the liBody variable, and I figure the HTML span element is the best way to do that, except I don't even know quite what the span element really does. How do I go about editing the style of that particular string? I can't get around to figuring out how (if I even can) make the text turn brown on mouseover until I do so.

Never met CreateTextNode, but i guessliBody.style.fontSize="12px"should help. And other properties such as 'fontWeight,color,fontStyle...'

HTML elements have a style property that can be used to apply CSS styles to them.
For example:
var newClickMe = document.createElement("span");
newClickMe.style.backgroundColor = "#000000";
newClickMe.style.color = "#FFFF00";
newClickMe.innerText = "Click Me";
var li = document.createElement("li");
var liText = document.createTextNode("#"+numOfNewCMs+
" new ");
li.appendChild(liText);
li.appendChild(newClickMe);
Will make the list item have a black background with yellow text.
For more details on the style property, MDN has a great section on it: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
And here is a reference page to translate CSS properties into their JavaScript equivalent: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Properties_Reference

I'm assuming you want the styles to change on mouseOver. I just changed the styles using css' :hover. Is this what you had in mind?
var numOfNewCMs=1;
function generateLi(){
var li = document.createElement("li");
var liBody = document.createTextNode("#"+numOfNewCMs+
" new ");
var sp = document.createElement("span");
var spBody = document.createTextNode("Click Me");
sp.setAttribute("id", "sp"+numOfNewCMs);
sp.setAttribute("onmouseover", "highlight("+numOfNewCMs+")");
sp.setAttribute("onmouseout", "highlight2("+numOfNewCMs+")");
sp.style.backgroundColor='black';
sp.style.color='yellow';
sp.appendChild(spBody);
li.appendChild(liBody);
li.appendChild(sp);
lis.appendChild(li);
numOfNewCMs++;
}
function highlight(id){
var element= document.getElementById('sp'+id);
element.style.backgroundColor='white';
element.style.color='brown';
}
function highlight2(id){
var element= document.getElementById('sp'+id);
element.style.backgroundColor='black';
element.style.color='yellow';
}
li{
margin-bottom:20px;
}
li > span{
padding:5px;
margin-bottom:10px;
}
li:hover > span{
color:brown;
background-color:white;
}
<button onclick="generateLi()">Click me</button>
<div id="lis" style="margin-top:20px;"></div>

Related

Creating text node and adding CSS

I'm attempting to create a text element and then add CSS attributes
I've tried to use the code below
function create(text){
var t = document.createTextNode(text);
t.style.color = "black"
t.style.backgroundColor="white"
t.style.borderRadius="20px"
t.style.border="4px solid black"
document.body.appendChild(t);
}
create("hello");
I expect to create a text with a white background and 20px border radius with a 4px solid black border
Instead of a text node, which I don't think you can add styles to, just use a span instead
function create(text){
var t = document.createElement("span");
t.innerText = text;
t.style.color = "black"
t.style.backgroundColor="white"
t.style.borderRadius="20px"
t.style.border="4px solid black"
document.body.appendChild(t);
}
create("hello");
You are having trouble because text nodes are not meant to be styled.
You should create a DOM element instead. I took your code and update it in order to create a <p> (the nearest element of text node I guess) with your CSS:
function create(text) {
var t = document.createElement('p');
t.innerText = text;
t.style.color = "black"
t.style.backgroundColor="white"
t.style.borderRadius="20px"
t.style.border="4px solid black"
document.body.appendChild(t);
}
create("hello");
You are on the right direction. The only thing you need to do is change document.createTextNode(text) with:
var t = document.createElement('span');
t.innerText = text;
\\...
document.body.appendChild(t);
The reason why your code doesn't work is that you can only style HTML tags, and the the text node you created only contains the string you added, without a surrounding tag.
For example:
<span>
hello
</span>
is a tag with some text with it, while the hello text in the middle is a TextNode.
Hope this makes sense.
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode

Adding and deleting a paragraph, displaying text briefly

After clicking on a specific place in an image map, the function add() should be run, a paragraph should be created, one should see "not available yet" in red for five seconds, and the paragraph should be deleted again.
function add() {
var x = document.createElement("P");
var t = document.createTextNode("This is a paragraph.");
x.appendChild(t);
document.body.appendChild(x);
setTimeout ( "del()", 5000 );
}
function del() {
removeChild() }
So there are a couple of things which are not correct.
1: how do you change the text to red? And to another font?
2: the del()function should remove the paragraph, but I don't know what to place there. Just removeChild(P) ? Wait... P isn't even a Child...
Could anyone help me with getting the desired result? (I mean, this: one should see 'not available yet' in red for five seconds, afterwards the paragraph should disappear.
to change the text to red using JavaScript:
para.style.fontFamily = 'Arial'
para.style.color = 'red'
to change the text to red using CSS:
CSS:
.mypara {
color: red;
font-family: Arial;
}
JS:
para.className = 'mypara'
to remove the paragraph:
var para = document.createElement("P");
function add() {
var t = document.createTextNode("This is a paragraph.");
para.appendChild(t);
document.body.appendChild(para);
setTimeout (del, 5000);
}
function del() {
para.parentNode.removeChild(para);
// or if you just need to empty the paragraph
// para.innerHTML = '';
}
To make that text red: There are two ways. Either you write:
x.style.color = '#ff0000';
Or you give it a class:
x.className = 'red_text'
... and define the style for that class in a stylesheet.
To remove the paragraph, just do the reverse of what you did to add it:
document.body.removeChild(x)
Take a look to this example.
1: how do you change the text to red? And to another font?
I suggest to use CSS for everything regarding style and simply assign the right class to the element. You can specify whatever you need. For example also use CSS for a fade in effect.
2: the del()function should remove the paragraph, but I don't know what to place there. Just removeChild(P) ?
I suggest to use a closure and pass parent and child in order to use parent.removeChild(child);. If you do not need nothing else you even could avoid to define another function.

add color dynamically to added text

i am working on this example of appendChild() method.but the difference is here i am trying to add more text to a div dynamically.that was all right.but the hard part is the text i want to add will be red in color.how can i do that?
i tried
text.setAttributes('color',"red");
But it didn't work.so,how this task can be done??please help,thanks!!!!
the full code is given below............
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function create_text(){
var mydiv = document.getElementById("mydiv");
var text = document.createTextNode(" New text to add.");
mydiv.appendChild(text);
}
</script>
</head>
<body>
<button onclick="create_text();">Create Text Node</button>
<div id="mydiv">Welcome, here is some text.</div>
</body>
</html>
You would normally have to use CSS properties, however, text nodes cannot have CSS properties applied to them. You therefore need another container element:
You can choose any container element you wish, e.g. div, span, etc. It just needs to be capable of containing a text node. Having an element then allows us to access the styles property and set various styles (the color attribute in your case).
→ jsFiddle
function create_text(){
var mydiv = document.getElementById("mydiv");
var container = document.createElement("span");
var text = document.createTextNode(" New text to add.");
container.appendChild(text);
container.style.color = "red";
mydiv.appendChild(container);
}
Further note:
the order of the color assignments and calls of appendChild is arbitrary. The following would also be possible:
function create_text(){
var mydiv = document.getElementById("mydiv");
var container = document.createElement("span");
var text = document.createTextNode(" New text to add.");
container.appendChild(text);
mydiv.appendChild(container);
container.style.color = "red";
}
mydiv.style.color = 'red';
or just in css
#mydiv { color: red; }
if you have other elements inside the div that you don't want to be red, you'd need to wrap the new text in a span or div or another element before appending.
with jquery this would be super easy:
$('#mydiv').append('<span style="color:red">this is new text</span>');
If that's everything in your div, you could try
document.getElementById("mydiv").style.color="#ff0000";

Centering three buttons in three divs on the same line

I have three buttons, inside three divs, and I need to center them on the same line.
They were created with the createElement() method. Button and Div.
This is the only way I know for creating buttons within functions or script tags or if-else statements. Or at least the only way that works for me. ^^;
I bet a visual would help at this point.
function threeGameButtons()
{
buttonDiv = createElement("div");
buttonDiv = setAttribute("center");
//This ^ has been to center the divs, and has done so by putting them on
//top of each other. I believe I understand why though.
gameButton = document.createElement("BUTTON");
gameText = document.createTextNode("text");
gameButton = appendChild(gameText);
buttonDiv.id = "buttonID";
gameButton.onclick = myFunction;
//calls a function for the game
buttonDiv.appendChild(gameButton);
document.body.appendChild(buttonDiv);
//two more buttons
}
So the three buttons made like this are called in a function earlier in the game. (I don't think I mentioned, but it's probably obvious now: this is for a game).
I'd love to just make a container div and center that or something but I'm completely unaware of how to do so when the divs are created like this in a function.
And I've tried some CSS to center the divs and buttons. Oh boy have I tried. But my efforts have been fruitless. I could give you everything, but I'd have to think back to all of the CSS methods I've tried.
One I've tried though:
#buttonID2 (Second and center button)
{
margin:0 auto;
}
#buttonID (First and left button)
{
display:inline-block;
position:absolute;
left:200px;
}
#buttonID3 (Third and right Button)
{
display:inline-block;
position:absolute;
right:200px;
}
When I try this, the third button goes to the second line, but goes to the right.
And I've tried adding inline-block to margin:0 auto; and it stops the second button from centering.
The other two still go left and right of the center though.
My intention isn't really to have them go that far to the left and right, but for right now, I just don't want them overlapping the middle button.
A note; All of this happens on the page that the function calling them happens. I'm not sure if that makes a difference or not. I thought I'd throw that in though, in case it does.
So you want to add three buttons inside a DIV tag, inline. If I understand your question correctly I think this is what you are looking for:
function threeGamesButton() {
var x =document.getElementById("box");
var btnSet = document.createElement("div");
btnSet.setAttribute("style","border: 1px solid black; width:800; height:300;" )
var firstButton = document.createElement("button");
firstButton.setAttribute("style","border: 1px solid black; width:200; height:250;" );
firstButton.setAttribute("onClick","myFunction1()" );
firstButton.innerText ="Button 1";
var secondButton = document.createElement("button");
secondButton.setAttribute("style", "border: 1px solid black; width:200; height:250;");
secondButton.setAttribute("onClick","myFunction2()" );
secondButton.innerText ="Button 2";
var thirdButton = document.createElement("button");
thirdButton.setAttribute("style", "border: 1px solid black; width:200; height:250;")
secondButton.setAttribute("onClick","myFunction3()" );
thirdButton.innerText ="Button 1";
btnSet.appendChild(firstButton);
btnSet.appendChild(secondButton);
btnSet.appendChild(thirdButton);
x.appendChild(btnSet);
}
In you html page include div which has id called box. And call the function from any where..Rather than setting a attribute for (styles), you can use
firstButton.className = "firstButton"
and then add css section for that name. But If the total width of the inside buttons are larger than the div tag where you insert all these buttons, then the last button will pass to the second raw automatically...
So I figured this out on my own, for anyone that needs it.
I have it here in JSFiddle.
But the part of the code for the buttons goes like this (ignore the odd function names) :
function continueIntro()
{
document.body.innerHTML = '';
var continueParagraph = document.createElement("p");
continueParagraph.innerHTML = "<center>These are the buttons I finally got <br>" +
"to center on the same line: </center>";
document.body.appendChild(continueParagraph);
getGoldButtons();
}
function getGoldButtons()
{
buttonDiv2 = document.createElement("div");
buttonDiv2.setAttribute("align","center");
gameButton2=document.createElement("BUTTON");
gameText2=document.createTextNode("First Option");
gameButton2.appendChild(gameText2);
buttonDiv2.id = "buttonDiv2";
gameButton2.onclick = caveGetGold;
buttonDiv2.appendChild(gameButton2);
gameButton3=document.createElement("BUTTON");
gameText3=document.createTextNode("Second Option");
gameButton3.appendChild(gameText3);
gameButton3.onclick = forestGetGold;
buttonDiv2.appendChild(gameButton3);
gameButton4=document.createElement("BUTTON");
gameText4=document.createTextNode("Third Option");
gameButton4.appendChild(gameText4);
gameButton4.onclick = tunnelGetGold;
buttonDiv2.appendChild(gameButton4);
document.body.appendChild(buttonDiv2);
}

Adding a diffent style to the end of a string

I think this is an easy question, but since I am new to javaScript...
I got an H1 innerHTML using this:
var myBeta = "Beta";
var myNode = document.getElementsByTagName("h1");
myNode[0].innerHTML = "New List of Materials " + myBeta;
How do I make the word "Beta" orange when concatenating the two text strings in the H1?
The problem is that their both in the same DOM node (in this case, the same h1) so you can't differentiate between the first and second word. What you have to do is put the word you want in orange in a separate span within the h1. Like this:
<h1>
This is black <span id="orange"> and this is orange</span>
</h1>
So your code should look like this:
HTML- empty h1 and span waiting for your JS to fill it
<h1><span id="orange"></span></h1>
CSS- making the span actually be orange
#orange {
color: orange;
}
JS
var myBeta = "Beta";
var blackWord = document.getElementsByTageName("h1");
var orangeNode = document.getElementById("orange");
blackWord[0].innerHTML = "New List of Materials";
orangeNode.innerHTML = myBeta;
You need to wrap the Beta string in another element:
var myBeta = "Beta";
var wrappedBeta = '<span style="color:orange">' + myBeta + '</span>';
var myNode = document.getElementsByTagName("h1");
myNode[0].innerHTML = "New List of Materials " + wrappedBeta;
Feel free to extract the style information in an external stylesheet and to change the span tag to something more semantically correct (strong for example).

Categories

Resources