javascript change element background - javascript

This is the HTML
<p>texjksdgfjl sdjfg sjdfg</p>
<p> </p>
<p>texjksdgfjl sdjfg sjdfg</p>
<p> </p>
<p>texjksdgfjl sdjfg sjdfg</p>
This is the JavaScript
var d = document.getElementsByTagName("p");
for (var i=0;i<d.length;i++)
{
var text = d[i].textContent;
if (text.length===1){
d[i].style.background ='blue';
}
else {
d[i].setAttribute("backgroundColor", "red");
}
}
(Obviously) I can do what I want to do - different background for p elements that contain some text as opposed to p elements which are generated as < p > & nbsp; < /p >
But why doesn't the setAttribute work?
I must be missing something very simple, but for the life of me I cannot imagine what it is.
Pure JS please, no jQuery, no MooTools, no other library.
Here is the test fiddle: enter link description here

Well, the setAttribute function doesn't do what you think it does.
If you inspect the elements in your jsfiddle, you see this:
... <p backgroundcolor="red" ...>
and this is definitely not what you want. What you want is something like this:
setAttribute("style", "background-color: red;");
so it will transform into
... <p style="background-color: red;" ...>

backgroundColor isn't an attribute on HTML elements. You can use bgcolor, but its really better to do this with CSS.
You can add a class to the node like this:
d[i].className += " myClass";
and then set a CSS rule
.myClass
{
backgroundColor: "red"
}
Or if you insist on hardwiring it to the DOM you can use
d[i].style.backgroundColor = "red"

Use:
d[i].style.setProperty("background", "red");
Instead of
d[i].setAttribute("backgroundColor", "red");

Assming Page instead of your element, you can read the below tutorial to change the background via javascript:
http://codeforbrowser.com/blog/changing-background-color-using-javascript-and-jquery/
<script type="text/javascript">
function changebackground() {
var colors = ["#0099cc","#c0c0c0","#587b2e",
"#990000","#000000","#1C8200","#987baa","#464646",
"#AA8971","#1987FC","#99081E"];
setInterval(function() {
var bodybgarrayno = Math.floor(Math.random() * colors.length);
var selectedcolor = colors[bodybgarrayno];
document.body.style.background = selectedcolor;
}, 3000);
}
</script>

You must do that:
var d = document.getElementsByTagName("p");
for (var i=0;i<d.length;i++)
{
var text = d[i].textContent;
if (text.length===1){
d[i].style.background ='blue';
}
else {
d[i].style.background ='red';
}
}
or
var d = document.getElementsByTagName("p");
for (var i=0;i<d.length;i++)
{
var text = d[i].textContent;
if (text.length===1){
d[i].style.background ='blue';
}
else {
d[i].setAttribute("style", "background-color:red;");
}
}
http://jsfiddle.net/3Lze5/6/

Related

How to change font colour on webpage with a button?

I was wondering if somebody could tell me how I can change my font colour of my webpage when a person clicks a button.
I have the functionality for the background but it doesnt seem to work for the text.
Here is my code so far:
<div class="dropdown">
<button onclick="toggleBackgroundDropdown()"
class="dropdownButton">Background</button>
<div id="backgroundDropdown" class="backgroundDropdown">
<a class="colorbutton">Red</a>
<a class="colorbutton">Yellow</a>
<a class="colorbutton">Blue</a>
<a class="colorbutton">White</a>
</div>
<button onclick="toggleTextColorDropdown()" class="dropdownButton">Text
Color</button>
<div id="textColorDropdown" class="textColorDropdown">
<a class="textcolorbutton">Red</a>
<a class="textcolorbutton">Yellow</a>
<a class="textcolorbutton">Blue</a>
<a class="textcolorbutton">White</a>
</div>
</div>
<script>
function toggleBackgroundDropdown()
{
document.getElementById("backgroundDropdown").classList.toggle("show");
}
function toggleTextColorDropdown()
{
document.getElementById("textColorDropdown").classList.toggle("show");
}
function changeColor()
{
var x = event.clientX;
var y = event.clientY;
var elementMouseIsOver = document.elementFromPoint(x, y);
document.body.style.backgroundColor = elementMouseIsOver.text;
}
function changeTextColor()
{
var x = event.clientX;
var y = event.clientY;
var elementMouseIsOver = document.elementFromPoint(x, y);
var a = document.getElementById('a');
a.style.color = elementMouseIsOver.text;
}
window.onload = function(event)
{
var colorbuttons = document.getElementsByClassName("colorbutton");
for (var i = 0; i < colorbuttons.length; i++)
{
colorbuttons[i].addEventListener('click', changeColor, false);
}
var textcolorbuttons = document.getElementsByClassName("textColorButton");
for (var i = 0; i < textcolorbuttons.length; i++)
{
textcolorbuttons[i].addEventListener('click', changeTextColor, false);
}
}
window.onclick = function(event)
{
if (event.target.className == "colorbutton")
{
toggleBackgroundDropdown();
}
else if (event.target.className == "textcolorbutton")
{
toggleTextColorDropdown();
}
}
</script>
Give an unique id for buttons like backgroundChange for the button. Then use the following code
$("#backgroundChange").click(function(){
if($(this).css('background-color')=='lightgrey')
$(this).css('background-color', 'red');
else {
$(this).css('background-color', 'lightgrey);
}
});
Similarly you can toggle the class
$("#backgroundChange").click(function () {
$(this).toggleClass('backgroundDropdown');
});
There is no need jquery, two way to do this:
define two classname with diff color, call function to change class onCLick
<p onclick="function(event){event.target.className = your new class"></p>
change your css style
<p onclick="function(event){event.target.style.backgroundColor = 'read'}"></p>
The better approach is to add/change the class of an element, i. e. the body and do the styling via CSS. More flexible, more robust.
If you are trying to change the text color on the whole page and it can be an arbitrary color (you can use classes as suggested by others, but only with a very limited set of choices), for example picking it with an <input type=color>, you'll have some trouble using just document.body.style.color = something. Unless you've added color: inherit pretty much everywhere.
A more thorough (though somewhat clunky due to the API design) approach is to change the rule that applies color in your stylesheet, a single rule with a big selector can ensure that you affect every element you wanted to:
const theRuleIndex = // here's the hard part, find the correct rule
document.styleSheets[0].cssRules[theRuleIndex].style.color = yourColor

Call <a> tag from css into javascript function

I am using this changing color script by j08691:
function flash() {
var text = document.getElementById('foo');
text.style.color = (text.style.color=='red') ? 'green':'red';
}
var clr = setInterval(flash, 1000);
I want to call the <body> tag and <a> tag from the CSS not an id.
For the <body> tag I did this and it works:
function flash() {
var text = document.body;
text.style.color = (text.style.color=='black') ? 'white':'black';
}
var clr = setInterval(flash, 1);
But it isn't working with the <a> tag. I tried variations like:
var els = document.getElementsByTagName('a');
var links = document.getElementsByTagName('a');
Instead of var text = document.getElementById('a'); and replacing text.style.color with links[i].style.color or links.style.color but I'm not quite sure what I'm doing there.
I want to change the colors of all links at once.
You are on the right track - getElementsByTagName returns a collection, so just loop through the collection:
function flash() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].style.color = (links[i].style.color=='black') ? 'white':'black';
}
}
setInterval(flash, 1000);
jsFiddle here
Also note that setInterval takes milliseconds, so setInterval(x, 1) isn't advised.
Are you trying to access the a tags in the html? and then apply some css to each via your function?
Using the jquery library
$("a").each(function(){
//do something with the element here like your function. $(this).stuff;
});

javascript to hide a div if empty

I am looking for javascript (not jquery as client has specified) to hide a div with class=top, if the div has no content. I can do it using jquery like below, but need to use javascript. Any ideas please?
$('div.top:empty').hide();
Something like:
var top = document.getElementsByClassName("top");
for (var i = 0; i < top.length; i++) {
if (top[i].innerHTML.length == 0)
top[i].style.display = "none";
}
you could use innerHTML property to check if the selected div.top element contains content. something like this.
var topDiv = document.getElementsByClassName('top')[0];
if(topDiv.innerHTML === '') {
topDiv.style.display = 'none';
}
(if(document.getElementById("yourDiv").innerHTML=="")
{
document.getElementById("yourDiv").style.display='none';
}
You need to give id to DIV which you want to hide As there are no function in javascript by which you can find div by class.
HTML:
<div class="top" id="divId"></div>
Javascript:
if( document.getElementById("divId").innerHTML == "" )
{
document.getElementById("divId").style.display='none';
}
Use the following script:
var divContent = $('div .top')[0].innerHTML;
if (divContent === '')
{
$('div .top').hide();
}

How to add a new rule to an existing CSS class

In the code below i have illustrated what I am trying to achieve...
Altering an existing CSS class by adding a new rule to it.
<head>
<style>
h4.icontitle
{font-size: 22pt;}
</style>
</head>
<body>
<script type="text/javascript">
textpercent = 84;
document.styleSheets[1].cssRules.['h4.icontitle'].style.setProperty('-webkit-text-size-adjust', textpercent+'%', null);
</script>
<h4> hello </h4>
</body>
This is for a pre-process element of a site running on screens of different sizes.
The result will be...
h4.icontitle
{font-size: 22pt;
-webkit-text-size-adjust:84%;}
Which will be visible when inspecting the DOM.
Any ideas would be most welcome. Javascript only - no JQuery here...
SOLVED.
After a lot of trial and error, here is a working function that allows javascript to insert styles directly into the CSS
function changeCSS(typeAndClass, newRule, newValue)
{
var thisCSS=document.styleSheets[0]
var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules
for (i=0; i<ruleSearch.length; i++)
{
if(ruleSearch[i].selectorText==typeAndClass)
{
var target=ruleSearch[i]
break;
}
}
target.style[newRule] = newValue;
}
Called with
changeCSS("h4.icontitle","backgroundColor", "green");
Hopefully others will find this a useful method to use variables within their CSS in pure javascript.
This function works perfectly for my site.
function changeCSS(typeAndClass, newRule, newValue)
{
var thisCSS=document.styleSheets[0]
var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules
for (i=0; i<ruleSearch.length; i++)
{
if(ruleSearch[i].selectorText==typeAndClass)
{
var target=ruleSearch[i]
break;
}
}
target.style[newRule] = newValue;
}
Called with
changeCSS("h4.icontitle","backgroundColor", "green");
/**
Use this to update style tag contents
**/
var css = 'h1 { background: grey; }',
head = document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
To work with elements within body use querySelector to target elements upon their CSS identifier. This should help you
https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
var el = document.querySelector(".icontitle");
el.setAttribute("style","-webkit-text-size-adjust:84%");
Or you can prepare a css snippet and use it conditionally ex: if "new_css" is the new change then
/**css code in style tag**/
.icontitle{
/**style at initial stage**/
}
.icontitle-new-modified{
/**modified css style at later stage**/
}
//after a condition is satisfied
el.setAttribute("class","icontitle-new-modified");
I put an example together that should suit your needs
DEMO jsFiddle
// this gets all h4 tags
var myList = document.getElementsByTagName("h4"); // get all p elements
// this loops through them until it finds one with the class 'icontitle' then it assigns the style to it
var i = 0;
while(i < myList.length) {
if(myList[i].className == "icontitle") {
myList[i].style.color="red";
}
i++;
}
Try this piece of code
$('h4.icontitle').css('-webkit-text-size-adjust','84%');

How can I make text bold with nodes and .createElement("b")?

I have to make text bold if I click on a button using nodes and createElement but I don't really know how...
html (This is the text I want to make bold):
<p id="textalt">Dies ist ein Text in einem P-Tag</p>
javascript:
function fettmachen(){
var neuB = document.createElement("b");
document.getElementById("textneu").insertBefore(neuB, document.getElementById("textneu").nextSibling);
}
I don't know how it works.
"I have to do it with nodes and createElement"
function fettmachen(){
// create the "b" element
var neuB = document.createElement("b");
// fetch the "textneu" element by ID
var textneu = document.getElementById("textneu");
// append the firstChild of "nextneu" to the "neuB"
neuB.appendChild(textneu.firstChild);
// append the "neuB" to the "nextneu"
nextneu.appendChild(neuB);
}
I suggest, instead of adding new tags, just use CSS, and add a class to the element.
CSS:
.boldText{
font-weight: bold;
}
JavaScript:
function fettmachen(){
document.getElementById("textalt").className += ' boldText';
}
I'd just put a style on the <p> tag on the button press. Maybe something like...
function fettmachen(){
var neuB = document.getElementById("textalt");
neuB.style.fontWeight = "bold";
}
Well, you could use the following code. It's longer and could be condensed - I find it clearer to read, personally.
function fettmachen()
{
var pElem = document.getElementById('textAlt');
var text = pElem.innerHTML;
var bElem = document.createElement('b');
bElem.innerHTML = text;
pElem.innerHTML = '';
pElem.appendChild(bElem);
}
This is how you make the text bold
function fettmachen(){
var p = document.getElementById("textneu");
p.style.fontWeight = "bold;"
}
If you have to use js for some reason for instance you need to only bold certain words maybe, and don't have access to the style sheet here you go. Otherwise use what Rocket has suggested.
Seriously only use a solution like this if at some point you will need to only bold certain words, or groups of words within an element.
function fettmachen(){
var neuB = document.createElement("b"),
textEl = document.getElementById("textalt"),
text = textEl.textContent;
neuB.textContent = text;
textEl.textContent = "";
textEl.appendChild(neuB);
}
Live Demo
And to unbold.
function unbold(){
var textEl = document.getElementById("textalt"),
boldEls = textEl.getElementsByTagName("b"),
text = "";
for(var i = 0; i < boldEls.length; i++){
text+=boldEls[i].textContent;
textEl.removeChild(boldEls[i]);
}
textEl.textContent = text;
}
Live Demo 2

Categories