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
Related
I have no idea how to change the colour of my element if the colour's crimson to white. It has me confused because I've tried many solutions such as turning them into variables. Would anyone be able to tell me what I'm doing wrong, or possibly point me in the right direction? I've tried "duplicate" questions, but none of them really share the same issue.
<button class="btn-startcall10" onclick="recorda()"><i class="fa fa-wave-square"></i> </button>
function recorda() {
document.getElementsByClassName("fa-wave-square")[0].style.color = "crimson";
if () {}
}
you can try something like this
function changeColor(){
el = document.getElementById("fa-wave-square");
if(el.style.color === 'crimson'){
el.style.color = 'white';
} else {
el.style.color = 'crimson';
}
}
https://jsfiddle.net/Lyuvf9a6/3/
You can use Element.style.color in the javascript to get the current color of the element.
Then based on that color you can change the color of your element.
let clickElement = document.getElementById("span-to-change-color");
clickElement.addEventListener("click", changeColor);
function changeColor() {
if (clickElement.style.color == "red") {
clickElement.style.color = "blue";
} else {
clickElement.style.color = "red";
}
}
<span style="color: red;" id="span-to-change-color">I am red(Click Me)</span>
First of all you have to add an event listener for on click event e.g
YOUR_ELEMENT.addEventListener("click", YOUR_LISTENER) // e.g recorda
Your event listener will get the event object from where you can access the object but if it's a nested object e.g your event listener is on div but you have a span inside and on click of span on click event will be triggered and the target object will be the span. But you can cache YOUR_ELEMENT and use that also.
Now you can check the style color for the color and do as necessary.
if (YOUR_ELEMENT.style.color === 'crimson') {
YOUR_ELEMENT.style.color = 'white'
} else {
YOUR_ELEMENT.style.color = 'crimson'
}
Here is a sample code e.g
<div id="textChange">Some text</div>
<script>
var elem = document.getElementsById('textChange')
function changeColor(e) {
// You can use and get elem using
// var ele = e.target
// Or as we have cached elem we can use that
if (elem.style.color === 'red') {
elem.style.color = 'green'
} else {
elem.style.color = 'red'
}
}
elem.addEventListener('click', changeColor)
</script>
I want to change the color of specific table cells when clicking a button.
<button onclick="highlight()">Toggle highlighting</button>
And JS:
function highlight() {
var x = document.getElementsByClassName('best');
for (var i = 0; i < x.length; i++) {
x.get(i).style.color = "green";
}
}
I added the table cells I want to change to the class "best", but when clicking the button, nothing changes. I first tried to assign them all to a single ID and use document.getElementById('best').style.color = "green";, but this only changed the first element that had the id "best" and not all. How should highlight() look like?
You don't need to use x.get(i) there. Just access the element using x[i]
See the following code:
function highlight() {
var x = document.getElementsByClassName('best');
for (var i = 0; i < x.length; i++) {
x[i].style.color = "green";
}
}
First off, I'd recommend using Javascript's built in forEach() function when working with a nodeList like this as there is less chance of an off by one error:
bestElements.forEach(best => {
best.style.color = "green";
});
Second, I believe you may be looking for the background-color attribute, not the color attribute if you are trying to change the color of the entire cell.
bestElements.forEach(best => {
best.style.backgroundColor = "green";
});
I was coding a website and was trying to change a few colors and pictures onclick using JavaScript to change the CSS. However this code is only partially working. Only the "txtArea" field changes color. Checked the validators and consoles its perfect syntax.??
<!-- This is the button to change the color, Its 1 bulletin point. -->
<div id="colorSelector"><span id="chngBlue">•</span> • •</div>
<script>
var colors = ["#0099cc", "#669900", "#993333"];//Blue, Green, Red
function chngColor(){
document.getElementById("txtArea").style.backgroundColor = colors[2];
document.getElementsByClassName("labHdr").style.backgroundColor = colors[2];
document.getElementById("newLink").style.color = colors[2];
document.getElementById("hdBanner").src='bannerred.png';
}
</script>
document.getElementsByClassName("labHdr") return a HTMLCollection (Thanks #Teemu for the clarification), so it haven't 'style'. You can do something like
var myElements = document.getElementsByClassName("labHdr");
for (var i = 0; i < myElements.length; i++) {
myElements[i].style.color = colors[2];
}
getElementsByClassName returns an array-like object, so you need to index into this array even if it only contains one element.
So the second line of the function becomes:
document.getElementsByClassName("labHdr")[0].style.backgroundColor = colors[2];
http://codepen.io/markwill/pen/rrAXzr
If there is more than one element with this class you'll need to iterate over all of them setting the style (this is safer than just assuming that there's just one).
Replace:
function chngColor(){
document.getElementById("txtArea").style.backgroundColor = colors[2];
document.getElementsByClassName("labHdr").style.backgroundColor = colors[2];
document.getElementById("newLink").style.color = colors[2];
document.getElementById("hdBanner").src='bannerred.png';
}
By that:
function chngColor(){
var labelList = document.querySelectorAll(".labHdr");
document.getElementById("txtArea").style.backgroundColor = colors[2];
document.getElementById("newLink").style.color = colors[2];
document.getElementById("hdBanner").src='bannerred.png';
Array.prototype.map.call(labelList, function(element) {
element.style.backgroundColor = colors[2];
});
}
With this all your labels will be change.
You can simply get element by id for change color below example which get more idea
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
I'm trying to make a site where users can create there own social networking buttons. (I know its been done but its mostly for practice). A part of the site will allow users to choose the shape of the buttons. Here is the HTML:
<div class="design" id="shape">
<div class="shapeSelect square" id="square"></div>
<div class="shapeSelect rounded" id="rounded"></div>
<div class="shapeSelect circle" id="circle"></div>
</div>
What I would like to do is add an event listener when the div is clicked. After it's clicked the class attribute would be changed to "selected." When another one would be click then the first clicked one would be cleared and the next one would be selected. Just like with radio buttons.
I am familiar with JavaScript and my idea was this:
window.onload = function () {
'use strict';
document.getElementById("square").addEventListener('click', function (e) {//adds the event listener
divArray = document.getElementById("shape");//Here is my first issue: an array is not returned
if (!(document.getElementById("square").getAttribute("class") == "shapeSelect square selected")) {// checks to make sure its not already selected
for (i = 0, count = document.getElementById("shape").length; i < count; i++) {// if it isn't go through the array
divArray[i]// and this is where i also get stuck. I Can't figure out how i would return the class attribute to be class="shapeSelect circle" instead of class="shapeSelect circle selected"
};
}
}, false);
}
A more simple version of scdavis41's answer:
$(document).ready(function(){
$('#shape > .shapeSelect').click(function(){
$('#shape > .shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
I also put a selector that includes the control's main div id in case you want to put this control more then once in your page.
** EDIT **
If you absolutly want to use javascript and DOM try this:
document.getElementById("square").addEventListener('click', function (e) {
var divArray = document.getElementById("shape").getElementsByTagName("div"); //Get all the div child element of the main div
for (i = 0, count = divArray.length; i < count; i++) {
if(divArray[i].getAttribute("class").indexOf("selected") !== -1) { //check if the selected class is contained in the attribute
divArray[i].setAttribute("class", divArray[i].getAttribute("class").replace("selected", "")); // clear the selected class from the attribute
}
};
document.getElementById("square").setAttribute("class", document.getElementById("square").getAttribute("class").concat(" selected")); //select the square
}, false);
This is verbose, but you could use:
$(document).ready(function(){
$('#square').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
$('#circle').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
$('#rounded').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
This is jQuery, which means you have to load the jQuery library, but putting this above your script tag:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
If you are looking for a pure JavaScript solution, you could try this:
if(option == 'add'){
element.className = element.className + ' selected';
element.onclick = function() {select(this.id, 'remove')};
element.innerHTML = '✓';
}
else if(option == 'remove'){
element.className = element.className.replace(/\bselected\b/,'');
element.onclick = function() {select(this.id, 'add')};
element.innerHTML = '';
}
JSFiddle: http://jsfiddle.net/hKePD/
**EDIT**
Or if you were looking for a checkbox to be always checked, you could try this: http://jsfiddle.net/hKePD/1/
Building on scadvis41's answer, this is much shorter:
$(document).ready(function(){
$('.shapeSelect').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
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/