Home > Net >  Change div border-color by clicking on div
Change div border-color by clicking on div

Time:04-16

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  id="A" onclick="fnChangeBorder('A')">Click here !!</div>

Thank you all very much.

CodePudding user response:

<!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 >Im green</div>
    <div >Im red</div>
    <div >Im green</div>
    <div >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>

CodePudding user response:

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  id="A" onclick="changeBorder('A', '#ff0000')">I'll be red</div>

<!-- Turns Green -->
<div  id="B" onclick="changeBorder('B', '#00ff00')">I'll be green</div>

CodePudding user response:

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

  • Related