lys916
lys916

Reputation: 317

disable click function on element depending on other element jquery

example..an NBA game. i want the user to choose a team within the game, once a team is clicked and highlighted or given a class of border, i want the opposite team to be un-clickable.

let say.. team-A vs Team-B.. i click on team-B, team-B is highlighted. now team-A is not clickable.. not until i click on Team-B again to toggle remove the border/highlight. and if i click on team-A, team-B will not be clickable

How would i go about doing this?

https://jsfiddle.net/mfvevgs5/5/

<div class="game game-1">
Game-1
  <div class="team road">
    <h3>
    Team-A
    </h3>
  </div>
  vs
  <div class="team home">
    <h3>
    Team-B
    </h3>
  </div>
</div>

<div class="game game-2">
Game-2
  <div class="team road">
    <h3>
    Team-C
    </h3>
  </div>
  vs
  <div class="team home">
   <h3>
    Team-D
    </h3>
  </div>
</div>

.border{
  border: 2px solid blue;
  width: 90px;
}

$('h3').on('click', function(){
    $(this).toggleClass('border');
});

Upvotes: 1

Views: 41

Answers (2)

Rajshekar Reddy
Rajshekar Reddy

Reputation: 18987

You can add a CSS rule to disable the pointer events on the teams that should be disabled. Here is a working Fiddle

$('h3').on('click', function(){
  $(this).closest('.game').find('h3').toggleClass('disable-team');
  $(this).toggleClass('disable-team').toggleClass('border');
});
.border{
  border: 2px solid blue;
  width: 90px;
}

.disable-team{
  pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="game game-1">
Game-1
  <div class="team road">
    <h3>
    Team-A
    </h3>
  </div>
  <div class="team home">
    <h3>
    Team-B
    </h3>
  </div>
</div>

<div class="game game-2">
Game-2
  <div class="team road">
    <h3>
    Team-C
    </h3>
  </div>
  <div class="team home">
   <h3>
    Team-D
    </h3>
  </div>
</div>

Upvotes: 1

BenG
BenG

Reputation: 15154

You need to check if any has the class which is not this.

$('h3').on('click', function() {
  var selectedTeams = $(this).closest('.game').find('.team h3.border');
  if (selectedTeams.not(this).length == 0)
    $(this).toggleClass('border');
});
.border {
  border: 2px solid blue;
  width: 90px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="game game-1">
  Game-1
  <div class="team road">
    <h3>
    Team-A
    </h3>
  </div>
  <div class="team home">
    <h3>
    Team-B
    </h3>
  </div>
</div>

<div class="game game-2">
  Game-2
  <div class="team road">
    <h3>
    Team-C
    </h3>
  </div>
  <div class="team home">
    <h3>
    Team-D
    </h3>
  </div>
</div>

Upvotes: 1

Related Questions