Reputation: 2971
Here in my program I have added an onclick listener to the table. What I want is that when the listener fires [when I click on a table cell], I want to disable the listener for that particular cell. Is there a possible way to do that other than adding listener to each td elements and removing the listener of the particular td when it fires.? My html looks like this :
<table id="board">
<tr>
<td id="c1"> 1</td>
<td id="c2"> 2</td>
<td id="c3"> 3</td>
</tr>
<tr>
<td id="c4"> 4</td>
<td id="c5"> 5</td>
<td id="c6"> 6</td>
</tr>
<tr>
<td id="c7"> 7</td>
<td id="c8"> 8</td>
<td id="c9"> 9</td>
</tr>
</table>
and the listener I added is like this :
var table = getId("board", 1);
table.addEventListener('click', sample , false);
function sample( evt ) {
alert(evt.target.innerHTML);
}
Upvotes: 0
Views: 424
Reputation: 318212
You can add an event handler direcly on the clicked element that stops the event from propagating
function sample(evt) {
alert(evt.target.innerHTML)
evt.target.addEventListener('click', function(e) {
e.stopPropagation();
});
}
Upvotes: 1
Reputation: 1076
You can use the 'one' function which adds the listener once.
HTML code:
<table id="board">
<tr>
<td id="c1" class="test"> 1</td>
<td id="c2" class="test"> 2</td>
<td id="c3" class="test"> 3</td>
</tr>
<tr>
<td id="c4" class="test"> 4</td>
<td id="c5" class="test"> 5</td>
<td id="c6" class="test"> 6</td>
</tr>
<tr>
<td id="c7" class="test"> 7</td>
<td id="c8" class="test"> 8</td>
<td id="c9" class="test"> 9</td>
</tr>
</table>
JS:
$('.test').one('click', function(){
alert('hi');
})
like this you have the listener on each cell until you click the particular cell
Upvotes: 0
Reputation: 193261
You can store some flag on those elements already clicked. For example in data attribute:
function sample(evt) {
var target = evt.target;
if (!target.getAttribute('data-clicked')) {
target.setAttribute('data-clicked', true);
alert(evt.target.innerHTML);
}
}
Upvotes: 2