I have the following code, and I want that when a number is clicked – contained within <span>
elements – it should change color, and when it's clicked again it should revert back to the original normal. I already found some online tutorials about changing color, and put some of that code to change color when clicked, but when it clicked it changed all the colors, not only the color of the element I wanted to change.
Could you show me how to make this happen, without setting all span with different id or class, because I have around 1000 span like this.
spans = document.querySelectorAll(".class");
for (const span of spans) {
span.onclick = function() {
document.execCommand("copy");
}
span.addEventListener("copy", function(event) {
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData("text/plain", span.textContent);
console.log(event.clipboardData.getData("text"))
}
});
}
body {
background-color: black;
color: white;
font-size: 20px;
padding-bottom: 475px;
padding-right: 150px;
}
::selection {
background: none
}
span:active {
color: purple
}
<span >444819751</span>
<span >444820170</span>
<span >444820588</span>
CodePudding user response:
First you can select your wanted elements with a querySelector and then you can add a event listener and get the reference of the clicked span like this
document.querySelectorAll('.allowClick span').forEach(occurence => {
occurence.addEventListener('click', (e) => {
if (e.target.style.color == "red")
e.target.style.color = "black"
else
e.target.style.color = "red"
});
});
<div >
<span>Allow click</span>
<span>11111111</span>
<span>222222222</span>
<span>AAAAAAAAA</span>
<span>BBBBBB</span>
<span>CCCCCC</span>
</div>
<br/>
<div>
<span>Dont allow click</span>
<span>11111111</span>
<span>222222222</span>
<span>AAAAAAAAA</span>
<span>BBBBBB</span>
<span>CCCCCC</span>
</div>
CodePudding user response:
Something like this should do the trick:
function changeColor() {
var text = document.getElementById("text");
if (text.style.color == "black") {
text.style.color = "red";
} else {
text.style.color = "black";
}
}
#text {
color: black;
}
<span id="text" onclick="changeColor()">Click me!</span>
CodePudding user response:
just very small change
spans = document.querySelectorAll(".class");
for (const span of spans) {
span.onclick = function() {
document.execCommand("copy");
}
span.addEventListener("copy", function(event) {
event.preventDefault();
if (event.clipboardData) {
event.clipboardData.setData("text/plain", span.textContent);
console.log(event.clipboardData.getData("text"))
}
});
span.addEventListener("click", function(event) {
event.preventDefault();
if(span.style.color === 'red'){
span.style.color = 'blue'
}else {
span.style.color = 'red'
}
});
}
body {
background-color: black;
color: white;
font-size: 20px;
padding-bottom: 475px;
padding-right: 150px;
}
::selection {
background: none
}
span:active {
color: purple
}
<span >444819751</span>
<span >444820170</span>
<span >444820588</span>