Change Colors (onclick) using Javascript - javascript

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>

Related

Image didn't change in jQuery setAttribute

i'm trying to change images based on the user pressing the next button but that isn't happening
var my_image = document.getElementById(main_image);
var image_array = ["https://www.w3schools.com/jsref/klematis2.jpg"];
var image_index = 1;
function change_image(){
my_image.setAttribute("src", image_array[image_index]);
image_index++;
if(image_index > 1){image_index = 0;}
}
<img src="https://www.w3schools.com/jsref/klematis.jpg" id ="main_image">
<button onclick="change_image()"> next </button>
document.getElementById() needs to have a string passed into it. If main_image is an element, and not a string, this could be your issue.
Looks like your array index is set wrong
There are 2 problems in your code:
1- getElementByID expects a string. By not putting quote marks around "main_image" javascript thinks main_image is a variable name, not a value.
2- your array only has one element, so it's position is 0, not 1.
Below your code is working:
var my_image = document.getElementById("main_image");
var image_array = ["https://www.w3schools.com/jsref/klematis2.jpg"];
var image_index = 0;
function change_image(){
my_image.setAttribute("src", image_array[image_index]);
image_index++;
if(image_index > 1){image_index = 0;}
}
<img src="https://www.w3schools.com/jsref/klematis.jpg" id ="main_image">
<button onclick="change_image()"> next </button>
Alternatively you can querySelector.
Secondly instead of using onClick in the button use addEventListener.
`
let my_image = document.querySelector("#main_image");
let nextBtn = document.querySelector("button")
let image_array = ["https://www.w3schools.com/jsref/klematis2.jpg"];
let image_index = 0;
const change_image =() => {
my_image.setAttribute("src", image_array[image_index]);
image_index++;
if(image_index > 1){image_index = 0;}
}
nextBtn.addEventListener("click", change_image)
`
The answer has been given, I'm only improving on the syntax
Pass a string into the document.getElementById(). I hope this works for you.

Change style of table cells on click

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

javascript: set onclick function with a parameter for a button

I have created a button using javascript and now I want to give it a onclick. however I want the function to have a parameter i. the problem is that when I inspect the console the onclick function is just onclick=playAudio(i). I want it to be different for each value of i in the for loop, but because it is in brackets it just stays as i instead of the current number in the for loop. I hope I have explained this properly. some of the code is below to help you understand.
var i;
var audioMp3 = ["audio/Un", "audio/Deux", "audio/Trois", "audio/Quatre", "audio/Cinq", "audio/Six", "audio/Sept", "audio/Huit", "audio/Neuf", "audio/Dix"];
for(i = 0; i < audioMp3.length; i++{
var audioBtn = document.createElement("BUTTON");
audioBtn.setAttribute("onclick", "playAudio(i);";
}
var audioMp3 = ["audio/Un", "audio/Deux", "audio/Trois", "audio/Quatre", "audio/Cinq", "audio/Six", "audio/Sept", "audio/Huit", "audio/Neuf", "audio/Dix"];
for(var i = 0; i < audioMp3.length; i++){
var node = document.createElement("BUTTON");
var textnode = document.createTextNode(audioMp3[i]);
node.appendChild(textnode);
node.setAttribute("onclick", "playAudio("+i+");");
document.getElementById("element").appendChild(node);
}
function playAudio(i){
alert(i);
}
<div id="element"></div>
I'm pretty sure that this should work :
audioBtn.setAttribute("onclick", "playAudio("+i+");");
audioBtn.onclick = function(){
playAudio(i)
}
Create an array with all the possible values, loop through the values to create the buttons, each button should have their click event listener to play their own button's song.
I don't know your precise code but that is the pseudo-code to do it.

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

Change color on all element using a css class

I try to change color in all elements in class, but I have an error:
Cannot convert undefined or null to object
I have code:
<div class="kolorek" onclick="changeColor('34495e');" style="background-color:#34495e;"></div>
function changeColor(color) {
var block = document.getElementsByClassName('kafelek');
with (block.style) {
backgroundColor = "#" + color;
}
};
As getElementsByClassName will return HTMLCollection, you have to loop through them to set the color as below.
function changeColor(color) {
var block = document.getElementsByClassName('kafelek');
for (var i = 0; i < block.length; i++) {
block[i].style.backgroundColor = "#" + color;
}
};
<div class="kolorek" onclick="changeColor('34495e');" style="background-color:#34495e;">Clickable Div</div>
<div class="kafelek">Another Div</div>
Note: Instead of inline onclick event, you can use addEventListener instead
Firstly you are searching for the wrong element and you can access style by using element.style and to change backgroundColor it should be element.style.backgroundColor=color
check this snippet
function changeColor(color) {
var block = document.querySelector('.kolorek');
console.log(block.style);
block.style.backgroundColor = "#"+color;
};
<div class="kolorek" onclick="changeColor('999999');" style="background-color:#34495e;">sdfdsfds</div>
Hope this helps
First of all, using with is not recommended and even forbidden since es5 in strict mode (See the link I posted in the comment above). Secondly you are targeting elements with kafelek as their class, but the class you are showing in your html is kolorek. The third error is that you are trying to set a property on a HTMLCollection, but that doesn't exist. It exists on a single element. You need to refactor your code to the following:
function changeColor(color) {
var block = document.getElementsByClassName('kolorek');
Array.prototype.forEach.call(block, function(el) {
el.style.backgroundColor = '#' + color;
}
};

Categories