I have two Red buttons. If you click a button the color should change to Green. If you click again it should return to Red.
Now I succeed to change the color of the first button, but not of the seccond button.
Has someone an idea?
I have already a java script that change the color of one button
var button = document.querySelector("button");
button.addEventListener("click", function() {
const curColour = button.style.backgroundColor;
if (curColour === 'red') {
button.style.backgroundColor = "green";
} else {
button.style.backgroundColor = "red";
}
});
button {
height: 40px;
width: 160px;
border: 4px;
border-radius: 20px 20px 20px 20px;
border-color: red;
color: yellow;
padding: 12px 15px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button1 {
background: red
}
.button1:hover {
background-color: green;
}
<button id="bGeneral" class="button1" name="bGeneral"><b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id="buttonP" class="button1" name="buttonP"><b>Plates</b></button>
Expect to be able to change color of both buttons
You can use toggleClass. Also use querySelectorAll this will give all the buttons. Then iterate this collection and add event listener to it. .Inside callback function use classList.toggle to add or remove the class
var button = [...document.querySelectorAll("button")].forEach((item) => {
item.addEventListener("click", function() {
this.classList.toggle('toggleButtonColor')
});
})
button {
height: 40px;
width: 160px;
border: 4px;
border-radius: 20px 20px 20px 20px;
border-color: red;
color: yellow;
padding: 12px 15px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button1 {
background: red
}
.button1:hover {
background-color: green;
}
.toggleButtonColor {
background: green;
}
<body style="background-color:#E3CEF6;">
<button id="bGeneral" class="button1" name="bGeneral"><b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id="buttonP" class="button1" name="buttonP"><b>Plates</b></button>
</body>
As Andreas already said in the comments. You need querySelectorAll instead of querySelector. That will give you a collection which you must loop through
var buttons = document.querySelectorAll("button");
for (const button of buttons) {
// ...
}
var buttons = document.querySelectorAll("button");
for (const button of buttons) {
button.addEventListener("click", function() {
const curColour = button.style.backgroundColor;
if (curColour === 'red') {
button.style.backgroundColor = "green";
} else {
button.style.backgroundColor = "red";
}
});
}
button {
height: 40px;
width: 160px;
border: 4px;
border-radius: 20px 20px 20px 20px;
border-color: red;
color: yellow;
padding: 12px 15px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button1 {
background: red
}
.button1:hover {
background-color: green;
}
<button id="bGeneral" class="button1" name="bGeneral"><b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id="buttonP" class="button1" name="buttonP"><b>Plates</b></button>
You are using two different way to deal with the click. Use either onclick or addEventListener. Here is an example.
I haven't improved the inside of your function tho. Look at #brk answer for opti
function showOrHide(id, name) {
const button = document.getElementById(id);
const curColour = button.style.backgroundColor;
if (curColour === 'red' || !curColour) {
button.style.backgroundColor = 'green';
} else {
button.style.backgroundColor = 'red';
}
}
button {
height: 40px;
width: 160px;
border: 4px;
border-radius: 20px 20px 20px 20px;
border-color: red;
color: yellow;
padding: 12px 15px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button1 {
background-color: red;
}
.button1:hover {
background-color: green;
}
body {
background-color: #E3CEF6
}
<button id="bGeneral" onclick="showOrHide(this.id, 'General')" class="button1" name="bGeneral">
<b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id="buttonP" onclick="showOrHide(this.id, 'Plates')" class="button1" name="buttonP"><b>Plates</b></button>
you can use id :
function showOrHide(id) {
var element = document.getElementById(id);
const curColour = element.style.backgroundColor;
if (curColour === 'red') {
element.style.backgroundColor = "green";
}
else {
element.style.backgroundColor = "red";
}
}
and in HTML:
<button id="bGeneral" onclick="showOrHide(this.id)" class="button1" name= "bGeneral" ><b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id = "buttonP" onclick="showOrHide(this.id)" class="button1" name= "buttonP" ><b>Plates</b></button>
This is the proper way with your thoughts
<!DOCTYPE html>
<html>
<head>
<style>
button {
height:40px;
width:160px;
border: 4px;
border-radius: 20px 20px 20px 20px;
border-color:red;
color: yellow;
padding: 12px 15px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button1 { background: red }
.button1:hover {
background-color: green;
}
</style>
</head>
<body onload="beginfase()" style="background-color:#E3CEF6;" >
<button id="bGeneral" onclick="" class="button1" name= "bGeneral" ><b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id = "buttonP" onclick="" class="button1" name= "buttonP" ><b>Plates</b></button>
<script type="text/javascript">
//we are creating an array
var button = [];
button = document.querySelectorAll("button");
//we are binding the function to all the elements of the array
for(i=0;i<button.length;i++){
button[i].onclick = function(){
// this represent the elemement which is being clicked
if(this.style.backgroundColor === "red"){
this.style.backgroundColor = "green"
}
else{
this.style.backgroundColor = "red"
}
}
}
</script>
</body>
try use onclick method, and use querySelectorAll to select all the buttons
HTML
<button id="bGeneral" onclick="changeColor(this)" class="button1" name= "bGeneral" ><b>General</b></button>
<!-- Create extra space -->
<p><br></p>
<!-- The Next Button Plates -->
<button id = "buttonP" onclick="changeColor(this)" class="button1" name= "buttonP" ><b>Plates</b></button>
JS
function changeColor (value) {
var buttons = document.querySelectorAll(".button1");
let color = value.style.backgroundColor;
for (let i = 0; i < buttons.length; i++) {
if (color === 'red') {
buttons[i].style.backgroundColor = 'green'
} else {
buttons[i].style.backgroundColor = 'red'
}
}
}
Related
Suppose I have 3 buttons:
.all-buttons{
display:flex;
width: 100%
}
.bttn{
width: 33%
border: none;
background-color: blue;
padding: 20px 20px;
color: white;
}
<html>
<head><title>yes</title></head>
<body>
<div class="all-buttons">
<button class="bttn">BUTTON1</button>
<button class="bttn">BUTTON2</button>
<button class="bttn">BUTTON3</button>
</div>
</body>
</html>
As of my understanding I can use JavaScript const buttons = document.querySelectorAll('bttn'); which will create an array with every element with the class 'bttn'. How do I change the style of a button? For example, say I want to change the background-color of Button2 if I click on it. How do I get Button2 using classes in javascript?
I have tried this:
const buttons = document.querySelectorAll('link');
Array.from(buttons).forEach(el => {
el.addEventListener('click', function(event) {
//code
});
});
My end goal is to create a drop-down menu for each of the buttons but I would like to avoid adding an id for each button.
Any input is appreciated.
For getting elements by className, you have 2 options:
getElementsByClassName (without ".")
const buttons = document.getElementsByClassName('bttn');
querySelectorAll (with ".")
const buttons = document.querySelectorAll('.bttn');
And for changing the style of an element, you can use .style property on that element:
element.style.backgroundColor = 'blue';
So this code will help you:
const buttons = document.querySelectorAll('.bttn');
Array.from(buttons).forEach(el => {
el.addEventListener('click', function(event) {
el.style.backgroundColor = "blue";
});
});
Read more here.
First, document.querySelectorAll('bttn'); will not get elements with class equal to .bttn but it gets the elements with tag name equal to bttn.
You need to add the . like document.querySelectorAll('.bttn');
Then, you need to loop through with forEach and on each button add an event listener with addEventListener method on click, then you can change the color with style or create a class for the color and use classList methods.
const buttons = document.querySelectorAll('.bttn');
buttons.forEach(button => {
button.addEventListener('click', () => {
button.classList.toggle('red');
})
})
.all-buttons{
display:flex;
width: 100%
}
.bttn{
width: 33%
border: none;
background-color: blue;
padding: 20px 20px;
color: white;
}
.red {
background-color: red;
}
<html>
<head><title>yes</title></head>
<body>
<div class="all-buttons">
<button class="bttn">BUTTON1</button>
<button class="bttn">BUTTON2</button>
<button class="bttn">BUTTON3</button>
</div>
</body>
</html>
Hope it helps!
const buttons = document.querySelectorAll('.bttn'); // You must declare element's type; class (.) or id (#).
Array.from(buttons).forEach(el => {
el.addEventListener('click', function(event) {
el.style.color = "red"; // Added the line for changing the style of the button.
});
});
<button class="bttn">BUTTON1</button>
<button class="bttn">BUTTON2</button>
<button class="bttn">BUTTON3</button>
i think you need,
change element using queryseletorall
dropdown menu to each button
without using id to each button
to achieve this try like below,
const nodeList = document.querySelectorAll(".dropbtn");
const submenuList = document.querySelectorAll(".dropdown-content");
//alert(nodeList.length);
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].addEventListener('click', function(event) {
submenuList[i].classList.toggle("show");
});
}
.dropbtn {
background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #ddd}
.show {display:block;}
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
Link 1
Link 2
Link 3
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
Link- 1
Link- 2
Link- 3
</div>
</div>
if any query please comment
Still learning so bear with me.
I am building a test project where I have a simple input that I show it on the same page as a list. (grocery or to do list project)
So when a user hits the ok button I create a new li inside a ul element. That goes ok.
I want to implement the following though: When the user clicks on the new element (li) I want to change the text decoration to line-though and show a trash icon where it will remove this li element by clicking on it.
I have managed to do that. The problem is that when the user clicks again on the new element (li) I get a second trash image.
I want help to succeed in this: when a user clicks on the element while it has text-decoration = line-through to hide or remove the trash icon and make text-decoration none again.
Here is a code pen for this project to check out. Just insert a new item on the list and then click twice on it: https://codepen.io/dourvas-ioannis/pen/MWVBjNZ
This is the function I am using when the user hits the add button to add a list item:
function addToList(){
let newListItem = document.createElement('li');
newListItem.textContent = userInput.value;
list.appendChild(newListItem);
userInput.value = "";
newListItem.addEventListener('click', function(){
this.style.textDecoration = 'line-through';
let itemButton = document.createElement('a');
itemButton.setAttribute('href', '#');
itemButton.classList.add('trash-image');
itemButton.innerHTML = '<i class="material-icons">delete</i><a/>';
itemButton.addEventListener("click", deleteOneItem);
this.appendChild(itemButton);
});
}
function deleteOneItem(){
this.parentNode.remove();
}
//select from DOM
let allItems = document.querySelector('#allItems');
let button = document.querySelector('#add-button');
let userInput = document.querySelector('#item');
let list = document.querySelector('#list');
let clear = document.querySelector('#clear-button');
//add event listener
button.addEventListener('click', addToList);
clear.addEventListener('click', clearAll);
//functions
function addToList() {
let newListItem = document.createElement('li');
newListItem.textContent = userInput.value;
list.appendChild(newListItem);
userInput.value = "";
newListItem.addEventListener('click', function() {
this.style.textDecoration = 'line-through';
let itemButton = document.createElement('a');
itemButton.setAttribute('href', '#');
itemButton.classList.add('trash-image');
itemButton.innerHTML = '<i class="material-icons">delete</i><a/>';
itemButton.addEventListener("click", deleteOneItem);
this.appendChild(itemButton);
});
}
function deleteOneItem() {
this.parentNode.remove();
}
function clearAll() {
list.innerHTML = "";
}
body {
font-size: 10px;
font-family: Arial, Helvetica, sans-serif;
margin: 0;
background-color: antiquewhite;
}
#container {
width: 80%;
margin: auto;
padding-top: 10px;
background-color: rgb(200, 225, 225);
color: rgb(52, 48, 48);
border-radius: 10px;
}
p {
font-size: 20px;
text-align: center;
padding: 30px, 0px, 5px, 0px;
}
#formdiv {
text-align: center;
}
#item {
size: 100px;
}
#clear {
margin-top: 60px;
text-align: center;
}
li {
list-style-type: none;
font-size: 3.2em;
padding: 0.5em;
margin: 1em;
background-color: lightyellow;
border-radius: 5px;
border: 1px solid grey;
}
.trash-image {
float: right;
margin: -2px 3px 3px 3px;
vertical-align: middle;
height: 4px;
}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<body>
<br> <br> <br>
<div id='container'>
<p>My list</p>
<br>
<div id="formdiv">
<label for="item">add this.. </label><br>
<input type="text" name="item" id="item">
<button id="add-button"> add </button>
</div>
<div id="allItems">
<ul id="list">
</ul>
</div>
<div id="clear">
<button id="clear-button"> Clear List </button><br> <br> <br>
</div>
</div>
Here's a quick example implementation of the approach I mentioned in the comments. I've just hacked it together quickly, so there's a small difference for the bin.
I've used an img (without a src) instead of a 'character' from the
font. I've styled the img to be 16x16 for the same reason. It also
makes it visible instead of being 0x0 pixels. I also set the cursor.
"use strict";
window.addEventListener('load', onLoad, false);
function onLoad(evt) {
document.querySelector('button').addEventListener('click', onAddBtnClicked, false);
}
function onAddBtnClicked(evt) {
let userText = document.querySelector('input').value;
let newLi = document.createElement('li');
newLi.textContent = userText;
newLi.addEventListener('click', onIncompleteItemClicked, false);
document.querySelector('ul').appendChild(newLi);
}
function onIncompleteItemClicked(evt) {
let clickedLi = this;
clickedLi.classList.toggle('itemComplete');
let binImg = document.createElement('img');
binImg.addEventListener('click', onBinIconClicked, false);
clickedLi.appendChild(binImg);
clickedLi.removeEventListener('click', onIncompleteItemClicked, false);
clickedLi.addEventListener('click', onCompletedItemClicked, false);
}
function onCompletedItemClicked(evt) {
let clickedLi = this;
clickedLi.classList.toggle('itemComplete');
let binImg = clickedLi.querySelector('img');
clickedLi.removeChild(binImg);
clickedLi.removeEventListener('click', onCompletedItemClicked, false);
clickedLi.addEventListener('click', onIncompleteItemClicked, false);
}
function onBinIconClicked(evt) {
let clickedBin = this;
let containingLi = clickedBin.parentNode;
containingLi.remove();
}
.itemComplete {
text-decoration: line-through;
}
li>img {
cursor: pointer;
width: 16px;
height: 16px;
}
<input value='blah-blah'></input><button>Add</button>
<ul></ul>
Add a variable indicating that the icon has been already added.
Check if icon is added on click
If yes - skip
If not - set icon
//select from DOM
let allItems = document.querySelector('#allItems');
let button = document.querySelector('#add-button');
let userInput = document.querySelector('#item');
let list = document.querySelector('#list');
let clear = document.querySelector('#clear-button');
//add event listener
button.addEventListener('click', addToList);
clear.addEventListener('click', clearAll);
//functions
function addToList() {
let newListItem = document.createElement('li');
newListItem.textContent = userInput.value;
list.appendChild(newListItem);
userInput.value = "";
// declare boolean variable
let hasTrashIcon = false
newListItem.addEventListener('click', function() {
// if has thrash icon skip
if (hasTrashIcon) return
// set has trash icon
hasTrashIcon = true
this.style.textDecoration = 'line-through';
let itemButton = document.createElement('a');
itemButton.setAttribute('href', '#');
itemButton.classList.add('trash-image');
itemButton.innerHTML = '<i class="material-icons">delete</i><a/>';
itemButton.addEventListener("click", deleteOneItem);
this.appendChild(itemButton);
});
}
function deleteOneItem() {
this.parentNode.remove();
}
function clearAll() {
list.innerHTML = "";
}
body {
font-size: 10px;
font-family: Arial, Helvetica, sans-serif;
margin: 0;
background-color: antiquewhite;
}
#container {
width: 80%;
margin: auto;
padding-top: 10px;
background-color: rgb(200, 225, 225);
color: rgb(52, 48, 48);
border-radius: 10px;
}
p {
font-size: 20px;
text-align: center;
padding: 30px, 0px, 5px, 0px;
}
#formdiv {
text-align: center;
}
#item {
size: 100px;
}
#clear {
margin-top: 60px;
text-align: center;
}
li {
list-style-type: none;
font-size: 3.2em;
padding: 0.5em;
margin: 1em;
background-color: lightyellow;
border-radius: 5px;
border: 1px solid grey;
}
.trash-image {
float: right;
margin: -2px 3px 3px 3px;
vertical-align: middle;
height: 4px;
}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<body>
<br> <br> <br>
<div id='container'>
<p>My list</p>
<br>
<div id="formdiv">
<label for="item">add this.. </label><br>
<input type="text" name="item" id="item">
<button id="add-button"> add </button>
</div>
<div id="allItems">
<ul id="list">
</ul>
</div>
<div id="clear">
<button id="clear-button"> Clear List </button><br> <br> <br>
</div>
</div>
I have a couple of buttons with one button that should disable all others. I wrote a code that selects buttons by adding a class and when clicked again deletes the class. It also pushed the value into an array. I want to make the no preference button in my code to delete a certain class from all buttons, except for the no preference button.
I already made it so it deletes everything in the array when it is clicked, but I just gotta delete the class from all buttons.
Code:
let div = document.getElementById('buttonDiv');
let arr = [];
div.addEventListener("click", function (event) {
let tgt = event.target;
function SelectedClass() {
if (tgt.classList.contains('Selected')) {
tgt.classList.remove('Selected');
} else {
tgt.classList.add('Selected');
}
}
if (tgt.classList.contains('buttons')) {
if (arr.indexOf(tgt.value) === -1) {
if (tgt.value === 'Ignore') {
if (tgt.classList.contains('Selected')) {
tgt.classList.remove('Selected');
} else {
tgt.classList.add('Selected');
arr = [];
}
} else {
SelectedClass();
arr.push(tgt.value);
}
} else {
arr.splice(arr.indexOf(tgt.value), 1);
SelectedClass();
}
}
console.log(arr);
})
.buttondiv {
position: relative;
width: 200px;
height: 675px;
margin-left: 50%;
transform: translateX(-50%);
margin-top: 50px;
}
.buttons {
width: 275px;
height: 50px;
display: inline-block;
margin-bottom: 15px;
;
border: 2px solid black;
border-radius: 3px;
background-color: white;
color: black;
}
.Selected {
background-color: orangered;
color: white;
border: none;
}
<div class="buttondiv" id="buttonDiv">
<button value="btn1" class="buttons">1</button>
<button value="btn2" class="buttons">2</button>
<button value="btn3" class="buttons">3</button>
<button value="btn4" class="buttons">4</button>
<button value="Ignore" class="buttons">No Preference</button>
</div>
I tried doing it with a for loop and a queryselector, but that didn't work. Does anybody know a solution?
If I understand you correctly the code can be simplified. See example below where different actions are taken place based on weather you press the no preference button or an other button. For this I added a class to the no preference button so we can easily query on that.
let div = document.getElementById('buttonDiv');
let arr = [];
div.addEventListener("click", function (event) {
let tgt = event.target;
if (tgt.classList.contains('buttons')) {
//when no preference is clicked remove all selected classes and empty the array
if(tgt.value === 'Ignore') {
event.currentTarget.querySelectorAll('.buttons').forEach((el) => {
el.classList.remove('Selected');
arr = [];
});
}
//when other button is clicked removed the selected class from the no preference button and push the current value to the array
else {
event.currentTarget.querySelector('.buttons.ignore').classList.remove('Selected');
arr.push(tgt.value);
}
//always add selected class to the current button.
tgt.classList.add('Selected');
}
console.log(JSON.stringify(arr));
})
.buttondiv {
position: relative;
width: 200px;
height: 675px;
margin-left: 50%;
transform: translateX(-50%);
margin-top: 50px;
}
.buttons {
width: 275px;
height: 50px;
display: inline-block;
margin-bottom: 15px;
;
border: 2px solid black;
border-radius: 3px;
background-color: white;
color: black;
}
.Selected {
background-color: orangered;
color: white;
border: none;
}
<div class="buttondiv" id="buttonDiv">
<button value="btn1" class="buttons">1</button>
<button value="btn2" class="buttons">2</button>
<button value="btn3" class="buttons">3</button>
<button value="btn4" class="buttons">4</button>
<button value="Ignore" class="buttons ignore">No Preference</button>
</div>
As you can see from my example i add a querySelectorAll to all button except for ignore button, when user click to "No Preference" forEach will disabled or enabled all.
let div = document.getElementById('buttonDiv');
let arr = [];
div.addEventListener("click", function(event) {
let tgt = event.target;
function SelectedClass() {
if (tgt.classList.contains('Selected')) {
tgt.classList.remove('Selected');
} else {
tgt.classList.add('Selected');
}
}
if (tgt.classList.contains('buttons')) {
if (arr.indexOf(tgt.value) === -1) {
if (tgt.value === 'Ignore') {
if (tgt.classList.contains('Selected')) {
tgt.classList.remove('Selected');
document.querySelectorAll('button:not(.ignore)').forEach(el => {
el.disabled = false;
});
} else {
tgt.classList.add('Selected');
document.querySelectorAll('button:not(.ignore)').forEach(el => {
if (el.classList.contains('Selected')) {
el.classList.remove('Selected');
}
el.disabled = true;
});
arr = [];
}
} else {
SelectedClass();
arr.push(tgt.value);
}
} else {
arr.splice(arr.indexOf(tgt.value), 1);
SelectedClass();
}
}
console.log(arr);
})
.buttondiv {
position: relative;
width: 200px;
height: 675px;
margin-left: 50%;
transform: translateX(-50%);
margin-top: 50px;
}
.buttons {
width: 275px;
height: 50px;
display: inline-block;
margin-bottom: 15px;
;
border: 2px solid black;
border-radius: 3px;
background-color: white;
color: black;
}
.Selected {
background-color: orangered;
color: white;
border: none;
}
<div class="buttondiv" id="buttonDiv">
<button value="btn1" class="buttons">1</button>
<button value="btn2" class="buttons">2</button>
<button value="btn3" class="buttons">3</button>
<button value="btn4" class="buttons">4</button>
<button value="Ignore" class="buttons ignore">No Preference</button>
</div>
Reference:
Document.querySelectorAll()
disabled
I'm having a problem with bluring the background when my menu is open. I tried writing something on my own but it's not working.
function backgroundBlur() {
var menuBox = document.getElementById("mobile-menu");
var blur = document.getElementById("body");
if (menuBox.style.dsiplay = "block") {
blur.style.filter = "blur(3px)";
}
}
I think the problem can be caused by three reasons:
Typo noted by #RyanWalls
The backgroundBlur() method is not called
The display property of the menuBox is not block
I made a run to simulate this event:
let button = document.getElementById('setBlur');
let control = false;
function backgroundBlur(control) {
var menuBox = document.getElementById("mobile-menu");
var blur = document.getElementById("body");
if (menuBox.style.display === "block")
{
if(!control)
{
blur.style.filter = "blur(3px)";
button.innerHTML = 'Remove Blur';
}
else
{
blur.style.filter = "blur(0px)";
button.innerHTML = 'Add Blur';
}
}
}
button.addEventListener('click', function() {
backgroundBlur(control);
control = !control;
});
*{
margin: 0;
}
#body{
background-color: black;
}
button{
margin-top: 25px;
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
width: 100%;
}
.vertical-menu {
width: 200px;
}
.vertical-menu a {
background-color: #eee;
color: black;
display: block;
padding: 12px;
text-decoration: none;
}
.vertical-menu a:hover {
background-color: #ccc;
}
.vertical-menu a.active {
background-color: #04AA6D;
color: white;
}
<div id="body">
<div id="mobile-menu" style="display: block;">
<div class="vertical-menu">
Home
Link 1
</div>
</div>
</div>
<button id="setBlur">Add Blur</button>
I am wondering if there is something that I can use instead of alert('Copied the hex value '+copyHex.value) to tell the user the message was copied? I don't like the way alert interrupts the page. I was wondering if 'copied (hex code)' who fade in above the color? I think this would look the best.
<!DOCTYPE html>
<html>
<head>
<title>
Color Generator
</title>
<style>
body{
margin: 0;
padding: 0;
background: #161818;
font-family: "Consolas";
}
.color{
margin-top: 300px;
text-align: center;
}
#hex{
display: block;
color: white;
font-size: 100px;
text-transform: uppercase;
margin: 0px;
}
.color button{
background: none;
outline: 10px;
color: white;
cursor: pointer;
font-size: 20px;
border: 3px solid white;
}
</style>
</head>
<body>
<div class="color">
<span id="hex">#??????</span>
<button onclick="genNewColor()">Generate new random color</button>
<button onclick="copyHexValue()">Copy hex value</button>
</div>
<script type="text/javascript">
function genNewColor() {
var symbols, color;
symbols = "0123456789ABCDEF";
color = "#";
for (var i = 0; i < 6; i++) {
color = color + symbols[Math.floor(Math.random() * 16)]
}
document.body.style.background = color;
document.getElementById("hex").innerHTML = color;
}
function copyHexValue() {
var copyHex = document.createElement('input');
copyHex.value = document.getElementById("hex").innerHTML;
document.body.appendChild(copyHex);
copyHex.select();
document.execCommand('copy');
alert('Copied the hex value '+copyHex.value)
console.log('Copied the hex value '+copyHex.value)
document.body.removeChild(copyHex);
}
document.body.onkeyup = function(e){
if(e.keyCode == 32){}
}
</script>
</body>
</html>
You can use a div with your custom message to notify your user.
I added an empty Notification div in your HTML and a CSS class for the same,
and removed alert("Copied the hex value " + copyHex.value);
Instead called a function to show the Notification
The Notification will appear at the top and will slide out after 2s (setTimeout)
PS Run the code snippet in full screen and if you want to outsource this try Material.io
Good Luck
function genNewColor() {
var symbols, color;
symbols = "0123456789ABCDEF";
color = "#";
for (var i = 0; i < 6; i++) {
color = color + symbols[Math.floor(Math.random() * 16)];
}
document.body.style.background = color;
document.getElementById("hex").innerHTML = color;
}
function copyHexValue() {
var copyHex = document.createElement("input");
copyHex.value = document.getElementById("hex").innerHTML;
document.body.appendChild(copyHex);
copyHex.select();
document.execCommand("copy");
// alert("Copied the hex value " + copyHex.value);
showNotification(copyHex.value);
console.log("Copied the hex value " + copyHex.value);
document.body.removeChild(copyHex);
}
document.body.onkeyup = function (e) {
if (e.keyCode == 32) {
}
};
const notification = document.querySelector(".notification");
function showNotification(color) {
let notificationText;
// If no color has been picked
if (color === "#??????") notificationText = "Generate a color first";
// Show Color Picked Message
else notificationText = `Copied hex value ${color}`;
//Slide down the notification
notification.style.transform = "translate(-50%,100%)";
// Add message to notification
notification.textContent = notificationText;
//Make Notification slide back up after 2s
setTimeout(function hideNotification() {
notification.style.transform = "translate(-50%,-100%)";
}, 2000);
}
body {
margin: 0;
padding: 0;
background: #161818;
font-family: "Consolas";
}
.color {
margin-top: 300px;
text-align: center;
}
#hex {
display: block;
color: white;
font-size: 100px;
text-transform: uppercase;
margin: 0px;
}
.color button {
background: none;
outline: 10px;
color: white;
cursor: pointer;
font-size: 20px;
border: 3px solid white;
}
.notification {
position: absolute;
left: 50%;
top: 0;
transform: translate(-50%, -100%);
transition: transform 0.6s ease;
border: 2px solid white;
padding: 12px 30px;
color: white;
}
<!DOCTYPE html>
<html>
<head>
<title>
Color Generator
</title>
</head>
<body>
<div class="color">
<span id="hex">#??????</span>
<button onclick="genNewColor()">Generate new random color</button>
<button onclick="copyHexValue()">Copy hex value</button>
</div>
<div class='notification'>
</div>
</body>
</html>
There are plenty of ways to do this. One of the simplest would be to add a DOM element above the hex and have it set to display:none; using a class called hidden
You could then set a timeout to show the element for a short time instead of an alert.
document.getElementById("hex-copy").classList.remove("hidden");
setTimeout(() => {
document.getElementById("hex-copy").classList.add("hidden");
}, 2500);
For a fade in, you could set CSS animations on the element.