Mahesh Mahesh - 1 month ago 10
HTML Question

Jquery change background colour for a selected div

I have this HTML code div in 4*4 format :



$(document).ready(function() {
$("div").click(function(e){

var id_val=this.id;

var word = id_val.split("-").pop();
alert(word)
e.preventDefault();

for(var i=1;i<=4;i++)
{
if(i!=word)
{
$("#div-"+i+"").css("background-color","white");
}
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div-1">
<p>div1</p>
<div id="div-2">
<p>div2</p>
<div id="div-3">
<p>div3</p>
<div id="div-4">
<p>div4</p>
</div>
</div>
</div>
</div>





I have written the jquery code when on click the particular div has to change colour to red and remaining div colour should be white

When I have executed this only the div1 has changing the colour to red and other divs are not changing the colour.

for eg :

if I click div1 change to red colour and other div2,div3,div4 should be in white
color
If I click div2 change to red colour and other div1,div3,div4 should be in white

color


Answer

You need to use e.stopPropagation(); to prevent the other div elements from triggering as well.

you didn't properly terminate the first two lines with }); at the end of the script.

  $(document).ready(function() {
    $("div").click(function(e) {

      var id_val = this.id;

      var word = id_val.split("-").pop();
      if (word != null) {
      alert(word)
      e.stopPropagation();

      for (var i = 1; i <= 4; i++) {
        if (parseInt(i) === parseInt(word)) {
          $("#div-" + i + "").css("background-color", "red");
      
        } else {
            $("#div-" + i + "").css("background-color", "white");
        }
      }
     }
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="div-1">
  <p>div1</p>
  <div id="div-2">
    <p>div2</p>
    <div id="div-3">
      <p>div3</p>
      <div id="div-4">
        <p>div4</p>
      </div>
    </div>
  </div>
</div>

Comments