user2584538 user2584538 - 5 months ago 11
Javascript Question

How to disable trigger click after first click

onclick
of the
a
elements I need to call a function and trigger
#myDiv
only once. Assume I am clicking 'Apple' any number of times it should trigger only one time. Then go to 'Orange' or 'Banana' and come back to 'Apple' again as same as earlier I need to trigger only one time. Assume there can be any number of
a
and those are dynamic. How can I achieve this?



function activateMyClick(myId) {
$('#myDiv').trigger('click');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a onclick="activateMyClick(7)" id="7" class="active">Apple</a>
<a onclick="activateMyClick(8)" id="8" class="active">Orange</a>
<a onclick="activateMyClick(9)" id="8" class="active">Banana</a>




Answer

A simple solution but I think works as you describe.

  • Multiple clicks on Apple, trigger fires only one time
  • After clicking on other links and then click again on Apple, trigger fires again only one time

var currentId = "";

function activateMyClick(myId) {
  if (currentId != myId) $('#myDiv').trigger('click');
  currentId = myId;
}

$('#myDiv').click(function() {
  console.log('div click raised!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onclick="activateMyClick(7)" id="7" class="active">Apple</a>
<a onclick="activateMyClick(8)" id="8" class="active">Orange</a>
<a onclick="activateMyClick(9)" id="8" class="active">Banana</a>
<div id="myDiv"></div>