codejourney
codejourney

Reputation: 319

How to change the color of the div depending on which button i click ? ( javascript/css/html ONLY no library)

i am trying to create a toast notification. I have 3 differents button and i want to change the color of the toast depending on which button i click. Note: the text you enter in the box is the text appearing in the toast.

Right now its all stacking up with the same color.

Heres the code ( the CSS is not good, i was just trying out things).

Can anyone help? Thanks a lot !

Upvotes: 0

Views: 130

Answers (2)

DarticCode
DarticCode

Reputation: 62

Simple Here \

document.getElementById( 'button1' ).addEventListener('click', function (event) {
console.log('green')
color('green', 'color')
}, false);
document.getElementById( 'button2' ).addEventListener('click', function (event) {
console.log('gold')
color('gold', 'color')
}, false);
document.getElementById( 'button3' ).addEventListener('click', function (event) {
console.log('blue')
color('blue', 'color')
}, false);
function color(color, id){
document.getElementById(id).style.backgroundColor=color;
}
#color{
width:150px;
height:50px;
background-color:black;
}
<div id ='color'></div>
<button id ='button1'>Green</button>
<button id ='button2'>gold</button>
<button Id="button3">blue </button>

Upvotes: 1

Almatrass
Almatrass

Reputation: 125

You can pass in a 'status' parameter to your function and determine the color to be used based on the status, like this:

function toast(status){
    const inputVal = document.getElementById("myInput").value;

    const container = document.getElementById("toastcontainer");

    const toastdiv = document.createElement("div");

    const toastColor = (status == 'error' ? 'red' : (status == 'success' ? 'green' : (status == 'info' ? 'blue' : '')));

    toastdiv.style.backgroundColor = toastColor;

    toastdiv.innerHTML = inputVal;
    container.appendChild(toastdiv);
}

then pass it in in your HTML:

<button type="button" value="Error" onclick="toast('error')">Error</button>

<button type="button" value="Success"onclick="toast('success')">Success</button>

<button type="button" value="Info"onclick="toast('info')">info</button>

Upvotes: 2

Related Questions