Javascript, change colour of element on-click with if-statement - javascript

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>

Related

Javascript Query All Selectors and do something

Goal:
Apply action to each checked element if checked, vs just the one element.
I am setting up multiple buttons (custom components) that when clicked, the border changes for the tag within . When clicked again, the border resets.
I have 'checked' properly displaying when I click on the flash-card-check-mark (elm), however my code is only selecting the first item and ignoring the rest.
Can you point me in the right direction as to how I would go about making sure that -- any -- of the buttons being clicked will have this action applied?
(new to javascript and appreciate your insight)
Note: This is for code example (doesn't run without the component checked but shows the markup I'm using -- I would share a link but this is running locally)
document.querySelector('flash-card-check-mark').onclick = function() {
var elem = document.querySelector('flash-card-check-mark');
var elemContent = document.querySelector('flash-card-check-mark p');
if (elem.getAttribute("checked") === null) {
elemContent.style.border = "1px solid #0000";
} else {
elemContent.style.border = "1px solid magenta";
}
};
<flash-card-check-mark no-default-padding="true">
<p align="left" size="small" class="pa-2">
<span slot="heading">Start my marketing today</span>
</p>
</flash-card-check-mark>
<flash-card-check-mark no-default-padding="true">
<p align="left" size="small" class="pa-2">
<span slot="heading">Create automated customer journeys</span>
</p>
</flash-card-check-mark>
You have two options:
Apply the click handler to all elements with querySelectorAll
Use Event Delegation to apply a handler to the document, and then only pick clicks that were on "interesting elements".
Apply to all elements
Use querySelectorAll:
for(const elem of document.querySelectorAll('flash-card-check-mark')) {
// better to use `element.addEventListener('click', (e) =>
element.onclick = function(e) {
// the element is available in the listener
var elem = e.target;
var elemContent = elem.querySelector('p'); // you can querySelector an element
if (elem.getAttribute("checked") === null) {
elemContent.style.border = "1px solid #0000";
} else {
elemContent.style.border = "1px solid magenta";
}
};
Use Event Delegation
You add a listener to the document instead and then filter the element out using e.target:
document.addEventListener('click', e => { // can also onclick
// filter only elements you care about
if (!e.target.matches('flash-card-check-mark')) return;
var elem = e.target;
var elemContent = e.querySelector('p'); // query selector nests
if (elem.getAttribute("checked") === null) {
elemContent.style.border = "1px solid #0000";
} else {
elemContent.style.border = "1px solid magenta";
}
};
Notes
You can improve the code style itself with the following advice:
Use let/const instead of var statements as they have much less confusing scoping rules.
Use arrow functions (() => {}) since they are shorter and have a more obvious this value.
Use addEventListener('click', to add event listeners instead of setting handlers with onclick. It has less confusing scoping rules and it means you don't have conflicts with other people setting handlers on the element.
Use properties instead of attributes. So elem.checked and not elem.getAttribute('checked') === 'checked').
If you want to select multiple element, Use querySelectorAll.
Query Selector all Returns a nodeList.
On that node list you can use forEach Loop
const flashCard = document.querySelectorAll("flash-card-check-mark");
const elemContent = document.querySelector("p");
function myFunction() {
if (elemContent.getAttribute("checked") === null) {
elemContent.style.border = "1px solid #0000";
} else {
elemContent.style.border = "1px solid magenta";
}
}
flashCard.forEach(flashcard => flashcard.addEventListener("click", myFunction));
Maybe something like this (I've changed the colors):
[...document.querySelectorAll('flash-card-check-mark')].forEach(el => {
el.onclick = () => {
var elemContent = document.querySelector('flash-card-check-mark p');
elemContent.style.border = el.getAttribute('checked') === null ? '1px solid red' : '1px solid green';
};
});
With var elemContent = document.querySelector('flash-card-check-mark p');
you always select the first matching element in the page
The click is behaviour of your Custom Element
Then the Custom Element should add and handle the click
If you want to select elements inside a Custom Element,
use this.querySelect... not document.querySelect...
Since you use shadowDOM <slot> also read ::slotted CSS selector for nested children in shadowDOM slot for
<flash-card-check-mark>
<span slot="heading">Start my marketing today</span>
</flash-card-check-mark>
<flash-card-check-mark checked>
<span slot="heading">Create automated customer journeys</span>
</flash-card-check-mark>
<script>
customElements.define("flash-card-check-mark", class extends HTMLElement {
constructor(){
let style = `<style>:host{display:block;cursor:pointer}</style>`;
super()
.attachShadow({mode:"open"})
.innerHTML = style + `<slot name="heading"></slot>`;
this.onclick = (evt) => this.clicked();
this.clicked();
}
clicked(){
this.toggleAttribute("checked", !this.hasAttribute("checked") );
let color = "pink";
if (this.hasAttribute("checked")) color = "lightgreen";
this.style.backgroundColor = color;
}
});
</script>

Javascript click to change background color and counting click

I have a problem. I have code as below:
const btnHappyOne = document.getElementById("happy-btn-1");
const btnHappyTwo = document.getElementById("happy-btn-2");
const btnHappyThree = document.getElementById("happy-btn-3");
function changeHappyBgColor(e){
let happyColor = e.target.style.backgroundColor;
if (happyColor != "red") {
e.target.style.backgroundColor = "red";
}
else {
e.target.style.backgroundColor = "";
}
}
btnHappyOne.addEventListener('click', changeHappyBgColor);
btnHappyTwo.addEventListener('click', changeHappyBgColor);
btnHappyThree.addEventListener('click', changeHappyBgColor);
This code change color of button when I click. My problem is that I want add some codes to count number of button whenever it change to red. When I click to change background color to none, the number of button also degrease. Thank you.
Add var number=0; below consts, in if block use number++; and in else block use number--;
You can track it in console to see the value, console.log(number);
I hope this is what are you asking for

Javascript is taking two clicks to initialize what I would like it to do

I'm creating a basic function that on click will allow a button that I have created to change its background color from a standard light gray I set with css to red with each click it should change from one to the other or vice versa. the issue I'm having is on the first click it stays light gray then the second click will turn it red and from there it will toggle on one click.
I'm trying this as a standard function "forgive me if that's not proper jargon for it" I'm also curious as to how this can be done as an arrow function since that was I could get it to change from light gray to red but not back to light gray.
let redBtn = document.getElementById('redBtn');
redBtn.addEventListener('click', function() {
const bgColor = redBtn.style.background;
if (bgColor == 'lightgray') {
redBtn.style.background = 'red';
} else {
redBtn.style.background = 'lightgray';
}
});
also the arrow function if you wouldn't mind providing insight to this issue as well thanks!
let red = document.getElementById('redBtn');
red.addEventListener('click', () => {
red.style.background = 'red';
if (red == 'lightgray') {
red.style.background = 'red';
} else {
red.style.background = 'lightgray';
`enter code here` });
On the first click, accessing the background property will return the empty string, even if CSS has set it to lightgray:
console.log(
document.querySelector('div').style.background === ''
);
.foo {
background-color: red;
}
<div class="foo">foo</div>
If you want to change it to red when the background is lightgray, check for if it's lightgray or the empty string:
let redBtn = document.getElementById('redBtn');
redBtn.addEventListener('click', function() {
const bgColor = redBtn.style.background;
if (bgColor == 'lightgray' || bgColor === '') {
redBtn.style.background = 'red';
} else {
redBtn.style.background = 'lightgray';
}
});
Or, it might be nicer to switch around the if/else - just check to see if the background is red, and if so, assign to lightgray. You can use the conditional operator here to reduce the amount of code, if you wanted:
let redBtn = document.getElementById('redBtn');
redBtn.addEventListener('click', () => {
const bgColor = redBtn.style.background;
redBtn.style.background = bgColor === 'red'
? 'lightgray'
: 'red';
});
An arrow function makes no difference here, because you're not referencing this or calling the function as a constructor.
const bgColor = redBtn.style.background;
Returns more than just the color. In fact it returns a string with up to eight properties.
So upon your first click, it doesn't match "lightgray" because the string it returns might be e.g. "lightgray none repeat scroll 0% 0%".
To only get the background color use this:
const bgColor = redBtn.style.backgroundColor;
Let's set the background to red like you wanted first:
// You wanted a function, so we added the onclick=""
<button id="redBtn" onclick="change()" style="background: red">Click</button>
Since you wanted an arrow function.
function change() { }
// Same as
change = () => { }
The ternary operator basically is saying:
bg === 'red' ? btn.style.background = 'lightgrey' : btn.style.background = 'red';
// Same as
if (background === red) {
// Change to lightgrey
} else {
// red
}
let btn = document.getElementById('redBtn'); // Get button
// Arrow function
change = () => {
const bg = btn.style.background; // Grab background color
// Ternary
bg === 'red' ? btn.style.background = 'lightgrey' : btn.style.background = 'red';
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<button id="redBtn" onclick="change()" style="background: red">Click</button>

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

Switching cell color based on current one using javascript

I am trying to change the cell color when a button is clicked. Here's my current code. (I am very new to this and am just messing around with things)
function changeColor() {
if(document.getElementById("changeColorId").bgColor = "yellow"){
document.getElementById("changeColorId").bgColor = "green";
} else {
document.getElementById("changeColorId").bgColor = "blue";
}
}
I am attempting to change the background color of 'changeColorId' to green if the current color is yellow (which it does do). However, I would also like it to change to blue if I click the button again, how would I go about doing this?
For comparisons use the equality operator ==, because = is an attribution. See Documentation for more.
Also, to access the element's css you have to access the style attribute, followed by the property in camelcase:
document.getElementById('elementId').style.property
I think that what you you want to reach is this:
function changeColor() {
if(document.getElementById("changeColorId").style.backgroundColor === "yellow"){
document.getElementById("changeColorId").style.backgroundColor = "green";
} else {
document.getElementById("changeColorId").style.backgroundColor = "blue";
}
}
Syntax
document.getElementById("changeColorId").bgColor
Following is correct syntax to get the color property of the element.
document.getElementById("changeColorId").style.color
Please check the code, Simple place code in html page it will work.
> <button onclick="changeColor();" >Click me</button>
> <div id="changeColorId" style="background-color:yellow">
> </div>
function changeColor() {
var elementStyle = document.getElementById("changeColorId").style;
if(elementStyle.backgroundColor == "yellow"){
elementStyle.backgroundColor = "green";
}
else if(elementStyle.backgroundColor == "green"){
elementStyle.backgroundColor = "blue";
}
else {
elementStyle.backgroundColor = "yellow";
}
}

Categories