'Change div border-color by clicking on div
I have a question regarding this given code: https://stackoverflow.com/a/34404172/11460885.
My situation is, I have different divs and some of them should have the border-color red, when clicking on them and some of them should be green.
How could I change the JS, so I can have more than on color, depending on the parameter?
JS:
function fnChangeBorder(boxId)
{document.getElementById(boxId).style.border = "solid #AA00FF";}
HTML:
<div class="box" id="A" onclick="fnChangeBorder('A')">Click here !!</div>
Thank you all very much.
Solution 1:[1]
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
.green-border {
border: green 0px solid;
}
.red-border {
border: red 0px solid;
}
.show-border {
border-width: 1px;
}
</style>
</head>
<body>
<div class="green-border">Im green</div>
<div class="red-border">Im red</div>
<div class="green-border">Im green</div>
<div class="red-border">Im red</div>
</body>
<script>
document.querySelectorAll(".green-border,.red-border").forEach((div) => {
div.addEventListener("click", () => {
div.classList.contains("show-border")
? div.classList.remove("show-border")
: div.classList.add("show-border");
});
});
</script>
</html>
Solution 2:[2]
You can create a second parameter in your function to do that
/*----- Defining Function ------*/
function changeBorder(elementID, colorHex){
/*----- Getting Element & Assign new borders ------*/
document.getElementById(elementID).style.border = "solid "+colorHex;
}
<!-- Turns Red -->
<div class="box" id="A" onclick="changeBorder('A', '#ff0000')">I'll be red</div>
<!-- Turns Green -->
<div class="box" id="B" onclick="changeBorder('B', '#00ff00')">I'll be green</div>
Solution 3:[3]
function fnChangeBorder(boxId)
{
var color = "";
if(boxId === 'A')
{color = "solid #AA00FF";}
else if(boxId == 'B')
{color = "solid black";}
document.getElementById(boxId).style.border = color;
}
This is really simple js, perhaps you should check out https://www.w3schools.com/js/js_if_else.asp
Solution 4:[4]
I did the same as others did, but I thought it is easier passing a config parameter in case you want to change other css properties here: HTML:
<div class="box" id="A" onclick="fnChangeBorder('A', config={type: 'solid', width: '20px', color: 'red'})">Click here !!</div>
JS:
function fnChangeBorder(boxId, config={})
{
//SETS DEFAULT VALUES IN CASE CONFIG VALUE IS UNDEFINED
const {type = "solid", width = "10px", color = "#000"} = config
document.getElementById(boxId).style.border = `${type} ${width} ${color}`
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nour Ashraf |
| Solution 2 | JamalThaBoss |
| Solution 3 | JBatstone |
| Solution 4 | EDev |
