Trying to create a function that will change to the same background color in two different HTML elements based on a random hex number

Viewed 31

Hello I am a junior at programming: I am trying to change background color to same color for two different HTML sections and I get two different colors although I have tried to select by class or by ID to the elements but always getting two different background colors. I believe my function generating the color is running twice , how can I make it to run just once and apply the same color to all the other functions? Thanks much for any help.

HTML

<h2>Overalls</h2>
<button class="button2" type="button" id="chOver"><span>Change Color</span></button> <img class="testo" id="overalls" src="img/overalls.png">
<div id="crazyDiv">
   <h1 class="testo" id="colorsp">#000000</h1>
</div>

Java Script

//overalls
let buttonSweet = document.getElementById("chOver")
    .addEventListener("click", buttonClick);

function buttonClick() {
    const randHex = Math.floor(Math.random() * 16777215).toString(16);
    document.getElementById('colorsp').innerHTML = "#" + randHex;
    return '#' + randHex;
}

let overallSweet = document.getElementById("chOver")
    .addEventListener("click", changeColOver);

function changeColOver() {
    $("#overalls").css("background-color", buttonClick);
}

let boxSweet = document.getElementById("chOver")
    .addEventListener("click", changeBoxCol);

function changeBoxCol() {
    $("#colorsp").css("background-color", buttonClick);
}
1 Answers

Perhaps this might solve the problem

function buttonClick() {
    const randHex = Math.floor(Math.random() * 16777215).toString(16);

    const generatedColor = '#' + randHex;
    
        document.getElementById('colorsp').innerHTML = generatedColor;
        
        $("#overalls").css("background-color", generatedColor);
        $("#colorsp").css("background-color", generatedColor);

        
}




document.getElementById("chOver")
    .addEventListener("click", buttonClick);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h2>Overalls</h2>
<button class="button2" type="button" id="chOver"><span>Change Color</span></button> <img class="testo" id="overalls" src="img/overalls.png">
<div id="crazyDiv">
   <h1 class="testo" id="colorsp">#000000</h1>
</div>

EDIT 1: it appears as you have added listener to the button twice.

Related