Change text color with Javascript? - javascript

I want to change the color of a title when a button is clicked.
This is my code, but it's not working and I can't figure out why not...
var about;
function init() {
about = document.getElementById("about").innerHTML;
about.style.color = 'blue';
}
<div id="about">About Snakelane</div>
<input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn">

You set the style per element and not by its content:
function init() {
document.getElementById("about").style.color = 'blue';
}
With innerHTML you get/set the content of an element. So if you would want to modify your title, innerHTML would be the way to go.
In your case, however, you just want to modify a property of the element (change the color of the text inside it), so you address the style property of the element itself.

use ONLY
function init() {
about = document.getElementById("about");
about.style.color = 'blue';
}
.innerHTML() sets or gets the HTML syntax describing the element's descendants., All you need is an object here.
Demo

Try below code:
$(document).ready(function(){
$('#about').css({'background-color':'black'});
});
http://jsfiddle.net/jPCFC/

innerHTML is a string representing the contents of the element.
You want to modify the element itself. Drop the .innerHTML part.

Related

How to apply a click function, that changes the clicked div, to new div elements that are created

At the moment I am using the following code which on the click of an HTML div element, changes the inner text to "Hello World":
<div id = "one" onclick = "click('one')" >text</div>
<script>
function click(id){
document.getElementById(id).innerHTML = "Hello World";
}
</script>
This works as expected and changes the content of the div to "Hello World".
The problem I am facing is at the moment I am using the id as a parameter input for the function and so that also means that for each div element that I create I would have to manually write its id within the onclick function.
I am able to create div elements using the following script which takes a value from an HTML input box, turns into a number then uses that number in a for loop to create as many div elements as specified:
<script>
function numberOfDivs(){
var divValue = parseInt(document.getElementById("inputbox").value, 10);
for(var i = 1; i < divValue + 1; i++){
var newDiv = document.createElement("div");
var divText = document.createTextNode("text")
//newDiv.setAttribute("onclick", "click()");
newDiv.appendChild(divText);
var whatIAmAppendingTo = document.getElementById("one");
whatIAmAppendingTo.appendChild(newDiv);
}
</script>
Now the problem that I having is applying that click() function to any of the new div elements that have just been created so that the click() function only affects the div that I have clicked on. I have included the setAttribute line when I create the new div elements so there is no problem linking it to the click() function.
I believe that there are two options:
-Either create new code within the numberOfDivs() function and use the var i to create an id that would be different for each new div element that I create, since var i increases to a different value each time the for loop repeats.
or
-Rewrite the click() function so that instead of having to use an id paramater I can instead make the function applicable to all div's. I was roughly thinking along the lines of using the 'this' keyword within that code, or anything along those lines so that it applies to only the div element that I click on.
With both of these possible solutions I'm not quite sure how to execute them so it would be great help if someone would be able to give me an example how it works.
Any questions or clarifications feel free to ask.
The problem I am facing is at the moment I am having to use the id as a parameter input for the function ...
No, you don't; you can pass this into your function, which is a reference to the div the click occurred on:
<div id = "one" onclick = click(this) >text</div>
Then in your function, use that argument rather than document.getElementById(id):
function click(div){
div.innerHTML = "Hello World";
}
Now you can use the same function for multiple divs.
Note, though, that if you're creating the divs programmatically, there's a better answer than setting the onclick attribute: addEventListener (attachEvent on older versions of IE). In your function creating divs:
var newDiv = document.createElement("div");
var divText = document.createTextNode("text")
if (newDiv.addEventListener) {
newDiv.addEventListener("click", click, false);
}
else {
newDiv.attachEvent("onclick", click);
}
Within click, use this:
function click(){
this.innerHTML = "Hello World";
}
typo in innerHTML and onClick
text
<script>
function click(id){
document.getElementById(id).innerHTML = "Hello World";
}
</script>
and
<div id = "one" onClick ="click('one')" >text</div>
Could this idea be helpful? Create your divs as (example for id='one'):
<div class='mydivs' id='one' ></div>
And then, detect the click on the div using a class and one event handler using JQuery:
$(".mydivs").click( function() {
id = $(this).attr('id');
click(id);
});
<div id="one">
<!-- dynamically added child nodes -->
</div>
<script>
$.ready(function(){
$('#one').children().livequery('click', function(event){
this.innerHTML = "Hello world";
});
});
<script>
Here we can use livequery to add click handlers to child elements that will be added dynamically.
if you provide your newly created divs with a common class e.g. clickable you could do this
$function(){
//Any click event of the body element that originates from a ".clickable"
//will be handled by the provided handler
$("body").on("click",".clickable",function(){
$(this).html("Hello world");
});
//... anything else that has to happen on document ready
});

need to display textarea after clicking label

When I click on a label, just below that some TextArea should be displayed with some predefined text in it and the user shouldn't able to modify the TextArea's content.
This is how I tried :
<html>
<head>
<script type="text/javascript">
function myfunc2() {
document.getElementById('showthis').style.visibility = "visible"
}
</script>
</head>
<body>
<label onclick="myfunc2()">Click here</label>
<textarea id="showthis" style="display:none">dfdsfsfasdfdsfsfasdfssdfsfasf</textarea>
</body>
</html>
iam new to this html and javascript.. pls someone help me on this..
try this..
document.getElementById('showthis').style.display = "block";
document.getElementById('showthis').readOnly=true;
updated
check for classname (hide).. if yes.. show the textarea and name it show ... else hide it and name the classname as hide
JAVASCRIPT
function myfunc2() {
var selectedobj=document.getElementById('showthis');
if(selectedobj.className=='hide'){ //check if classname is hide
selectedobj.style.display = "block";
selectedobj.readOnly=true;
selectedobj.className ='show';
}else{
selectedobj.style.display = "none";
selectedobj.className ='hide';
}
}
add a hide class to your html textarea.
HTML
<textarea id="showthis" style="display:none" class="hide">dfdsfsfasdfdsfsfasdfssdfsfasf</textarea>​ // add a class hide
Although you are setting visibility:visible, the element still has the style property display:none and therefore won't be displayed.
Rather than setting the visibility property, you should override the display property with block.
Change your function to:
function myfunc2() {
document.getElementById('showthis').style.display = "block";
}
You want to change the display property, not the visibility one, so replace your following line:
document.getElementById('showthis').style.visibility="visible"
for this one:
document.getElementById('showthis').style.display="block"
See working demo.
CSS attributes display and visibility are different.
It make more sense to use visibility if you want to simple make the element inivisible but keep the place it occupies in the layout, leaving a blank space:
<textarea id="showthis" style="visibility:hidden">dfdsfsfasdfdsfsfasdfssdfsfasf</textarea>
http://www.w3.org/wiki/CSS/Properties/visibility
On the other hand, using display will hide the element but also remove it from the layout:
function myfunc2() {
document.getElementById('showthis').style.display="block";
}
http://www.w3.org/wiki/CSS/Properties/display
youre missing a
;
on
document.getElementById('showthis').style.visibility="visible"
also you need to change the display.style not the visibility of the element
try this one
document.getElementById('showthis').style.display = "block";
or append a visibility="false" attribute to your textarea

How to add Tags in text node with Javascript

This is probably very easy/obvious.
I'm writing a Chrome extention.
My Javascript catches the text nodes from any site and changes part of the text to something else. I would like to mark the changed text by changing its color (adding tags).
return "<font color = \"FF0000\">"+a+"</font>"
And the result:
<font color = "FF0000">SomeText</font>
But all I want of course is that the SomeText will appear in red.
I recommend you use CSS in your chrome extension. so my solution would involve giving the DOM element (for your instance maybe its a paragraph or a span) a class. It's not good conventions to put style attributes in your HTML markup.
<p class="red">SomeText</p>
And in your CSS file
.red {
color: #ff0000 /* I actually love this color */
}
So how does this use JavaScript?
Instead of adding the styles directly into the HTML tag, you can instead add a class to an element.
document.getElementByTagName("p").className = "red";
Or if you want to target a specific ID
document.getElementById("object").className = "red";
And that text will be red. And since you can add the red class to any class attribute for any object in the DOM, your code will look cleaner than throwing styles everywhere.
I hope this helps you out. Let me know if otherwise.
function newText(tag, text, style) {
var element = document.createElement(tag); //this creates an empty node of the type specified
element.appendChild(document.createTextNode(text)); //this creates a new text node and inserts it into our empty node
if (style) element.setAttribute('style', style); //this sets the style in inline CSS (warning, this needs different syntax in IE)
return element; //this returns a DOM object
}
This will return a DOM object, and you will need to append it to another node.
var myText = newText('p', 'This is some text!', 'color: red;');
document.getElementById('myTextBox').appendChild(myText);
You need to add color in your style sheet...
Like <input type="text" style="color:red" value="sometext"/>.

Why are only some attributes updated from my javascript function?

I have a button script to change the buttons in a frame based on the page loaded in the main frame. The problem I'm experiencing is that while the background images, tabindex and text on the button (innerHTML) all change as expected, the onclick doesn't. It appears to completely ignore it. Here's the script I'm using:
function createbutton(btn_N, btn_I, btn_L, btn_D) // (Div Name, Tab Index, Button Text, Page To Load){
var btnN = top.frames['buttonbar'].document.getElementById(btn_N);
btnN.style.cssText = "display:block; cursor:pointer; padding-left:16px; padding-top:5px;";
btnN.onmouseover = function() {this.style.backgroundImage = "url('./osdimages/navBG_roll.png')";};
btnN.onmouseout = function() {this.style.backgroundImage = '';};
btnN.tabindex = btn_I;
btnN.innerHTML = btn_L;
btnN.onclick = btn_D;
}
The button call looks like this:
createbutton("button01", 1, "New Order/Browse", "parent.frames['content'].location.href='createorder/createorder.asp';");
There is a difference between attributes and properties.
The best example of this is as follows:
HTML: <input type="text" value="hello" id="test" />
Type something in the text box
document.getElementById('test').value is whatever you typed
document.getElementById('test').getAttribute("value") is whatever was in the HTML
Some attributes are directly mapped to properties and vice versa, but this is not always the case.
For instance, the onClick attribute takes a string that is then eval'd, but the onclick property takes a function. This is why your code isn't working.
Either pass a valid function, or use setAttribute.
You are setting onclick with a string, it needs a function to execute.
createbutton("button01", 1, "New Order/Browse", function(){ parent.frames['content'].location.href='createorder/createorder.asp'; });

Cannot figure out onMouseOver

I'm just messing around learning about JavaScript and I wanted to change the color of my background by resting my mouse over a link. Really I just want to learn about onMouseOver. I have:
Visit W3Schools
I tried applying this to radio buttons too that would change the bg color onclick, however If I wanted a preview of the color (by using onMouseOver) that part didn't work as it doesn't with the above.
Is the solution so obvious I'm overlooking it? Thanks for any help.
No, it's not obvious. JavaScript is not so easy to handle. And you have to learn the types and names of the objects you can use in JavaScript.
The object document does not have a element bgcolor
What you are trying is to change the CSS-style of the element body of the document
document.body.style.backgroundColor = 'lightgreen';
One could do it by using the document object model (DOM) which is what you tried, but you have to respect the case. the correct form of the document's attribute is bgColor not bgcolor (Capital letter C).
// bad style
document.bgColor = 'lightgreen';
But it is not advisable. Why?
document is a part of the Document Object Model (DOM) and therefore
mostly responsible for the data and the structure of the ... well
... document. The bgColor attribute of document maybe a relic of
the dark HTML medieval, the pre CSS times.
The document should contain the data, and not the representation (aka style) of the data. That what the style attribute of every DOM element is for.
You can overrule the bgColor of the document simply by giving the body a CSS style for background-color. The document still has the bgColor attribute and the value, but what you see is the value of the CSS style
onmouseover needs to be all lower-case onmouseover and it needs to equal a function (object.onmouseover=function(){//some code...} if in its own file and onmouseover="functionName()" if inline)
Here's an example: updated http://jsfiddle.net/TH2u3/1/
the following works:
<!DOCTYPE html>
<html>
<head>
<script>
var p = {
onload: function() {
var a = document.getElementsByTagName("a")[0];
a.onmouseover = function() {
document.body.style.backgroundColor = "blue";
};
a.onmouseout = function() {
document.body.style.backgroundColor = "green";
};
}
};
</script>
</head>
<body onload="p.onload()">
Visit W3Schools
</body>

Categories