I am new to JavaScript. I want to change the background color of the div element which is in a loop. On each click of the div element, the background color should change to blue color. I have tried using CSS, it works. I wish to implement it in Javascript. I want to change the background color of the selected div. But my code changes the background color of the previous selected and currently selected div.
What I have tried is:
Twig code:
<div class="inbox_chat">
{% set newArray = [] %}
{% for msg in msg_details %}
{% if msg.to_name not in newArray %}
<div class="chat_list active_chat" tabindex="{{loop.index}}" id="{{loop.index}}" onclick="viewMessage('{{loop.index}}')" >
<div class="chat_people">
<div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>
<div class="chat_ib">
<h5>{{msg.to_name}} <span class="chat_date">{{msg.time}}</span></h5>
</div>
</div>
</div>
{% set newArray = newArray|merge([msg.to_name]) %}
{% endif %}
{% endfor %}
</div>
Javascript code:
<script>
function viewMessage(elementId)
{
var e = document.getElementById(elementId);
var c= window.getComputedStyle(e).backgroundColor;
if (c === "rgb(235, 235, 235)")
{
document.getElementById(elementId).style.backgroundColor = "blue";
} else
{
document.getElementById(elementId).style.backgroundColor = "rgb(235, 235, 235)";
}
}
</script>
My code changes the background color of the currently selected and previously selected div elements.
What my output is:
How to change the background color of selected div only without changing another div background color?
CodePudding user response:
You should be using getPropertyValue
to get the value of a computed property:
function viewMessage(elementId) {
var e = document.getElementById(elementId);
var c = window.getComputedStyle(e).getPropertyValue('background-color');
if (c === "rgb(235, 235, 235)") {
document.getElementById(elementId).style.backgroundColor = "blue";
} else {
document.getElementById(elementId).style.backgroundColor = "rgb(235, 235, 235)";
}
}