Home > database >  I want to change the link color randomly when i click on it. Is there any way i can do it without us
I want to change the link color randomly when i click on it. Is there any way i can do it without us

Time:12-22

                <div >                  
                    <div id="link"><a>My Name</a></div>
                    <div >My Career</div>
                </div>

I tried to search for an answer but am just getting how to only change the background or with a button.

CodePudding user response:

Yea probably

<script>
    function changeLinkColor() {
        // Generate a random color in the format '#RRGGBB'
        let randomColor = '#'   Math.floor(Math.random() * 16777215).toString(16);

        // Get the link element
        let link = document.querySelector("#link a");

        // Set the link color to the random color
        link.style.color = randomColor;
    }
</script>

CodePudding user response:

You can try this in any case:

function generateColor(){
  return Math.floor(Math.random() * 255);
}

document.querySelectorAll('.anchor').forEach(el => {
      el.onclick = function(e){e.target.style.backgroundColor = 'rgb('  generateColor()   ','   generateColor()   ','  generateColor()   ')';
  }
});
.anchor{
  display: inline-block;
  background:dodgerblue;
  text-decoration: none;
  color:#fff;
  border-radius: 10px;
  text-shadow: 0 0 2px #000;
  padding: 10px;
  margin:10px
}
<a  href="#">click 1</a>
<div  href="#">click 1</div>
<p  href="#">click 1</p>

Please check this solution and let me know if its help you in any way.

  • Related