skip to Main Content

I want to change the divs rgb value in my website. For example I want to change value of red. How can I do it? Here is an example of my try.
I tried to change the red color value of div I named divcolor. But It didn’t work.

html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>dev</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <button id="button">hdsfs</button>
    <div id="divcolor">hellomf</div>
    <script src="js.js"></script>
</body>
</html>

css :

#divcolor {
    float:left;
    background-color: rgb(0,0,0);
    border-radius: 50%;
    width: 400px;
    height: 400px;
    position: absolute;
    overflow: hidden;
}

javascript :

let divcolor = document.getElementById('divcolor');
let button = document.getElementById('button');

function changeColor() {
    let redval = 0;
    let green = 0;
    let blue = 0;
    let color = 'rgb('+redval+","+green+","+blue+')';
    document.getElementById("divcolor").style.backgroundColor = color;
}
function minusred() {
    redval += 100
}


button.addEventListener("click",minusred, changeColor);

3

Answers


  1. what error do you get?
    I notice that you try to change the redval value, but that variable is not known in the scope of the minusred function.
    Also, you should only pass one handler at the adEventHandler instead of two.

    Login or Signup to reply.
  2. Try this:

    let divcolor = document.getElementById('divcolor'); 
     let button = document.getElementById('button'); 
     var redval=0; 
     var green = 0; 
     var blue = 0; 
     function changeColor() {
     redval += 100; 
     let color = 'rgb('+redval+","+green+","+blue+')';
     document.getElementById("divcolor").style.backgroundColor = color;
     }
     button.addEventListener("click",changeColor);
    
    Login or Signup to reply.
  3. This issue is mainly because you there is no connection between the redval in your change color function and the redval in the minusred function , also build the css property as a template string to pass in the values correctly.

    the corrected js would be

    let divcolor = document.getElementById('divcolor');
    let button = document.getElementById('button');
    
    function changeColor(redval,green,blue) {
        let color = `rgb(${redval},${green},${blue})`;
        document.getElementById("divcolor").style.backgroundColor = color;
    }
    function minusred() {
        let redval = 0;
        let green = 0;
        let blue = 0;
     
        redval += 100
        changeColor(redval,green,blue);
    }
    
    
    button.addEventListener("click",minusred);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search