• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

69
Views
How to change background color of div in loop in twig using javascript

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:

Output

How to change the background color of selected div only without changing another div background color?

about 1 month ago ·

Juan Pablo Isaza

1 answers
Answer question

0

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)";
    }
}
about 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.