-1

I'm building an app.net page using jQuery for DOM manipulation (JS Fiddle here). When I click a certain <td> on the table it becomes target for future manipulation. I want to add code, so that a click anywhere outside the table will un-target that <td> (meaning a click in the background should act as a cancel selection event).

The answers to this question did not help me, because: A. I don't want to use stopPropagation() because of this article plus I have many click event handlers in my code that I will have to stop from propagating). B. I have other elements on the page (buttons, text-input fields) which should NOT act as a cancel selection event).

Community
  • 1
  • 1
OzW
  • 848
  • 1
  • 11
  • 24
  • 1
    it would really help if you only leave the summary from your question, and replace that whole unnecessary wall of text with a working example and a link to the other discussion that you have mentioned. – Banana Jul 25 '15 at 17:09
  • edited my question... thanks for the comment. – OzW Jul 25 '15 at 19:52

1 Answers1

1

Without more specifics it seems like toggling an active class on target cells would do what you are suggesting.

var $table = $('#myTable').on('click', 'td', function(){
    $table.find('.active').removeClass('active');
     $(this).addClass('active');
});

Then for removing using events outside table just check if target is in the table

$(document).click(function(e){
  if(!$(e.target).closest('#myTable').length){
      $table.find('active').removeClass('active');
  }
});
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • thanks for the comment. I tried this, but as I mentioned - I have other elements on my page (button and text fields) and I do not want them to trigger `removeClass`. – OzW Jul 25 '15 at 19:54
  • Then you need to provide a lot more detail in the form of sample html...in a demo....jsfiddle.net, plnkr.co etc. Could also exclude clicks on form as target – charlietfl Jul 25 '15 at 19:56
  • added JSFiddle with all the neccesary data. – OzW Jul 25 '15 at 21:10
  • OK ...added one extra selector in `closest()` ....https://jsfiddle.net/nLLw0why/ could narrow that down more to `#container :input, #container button` also – charlietfl Jul 25 '15 at 21:16
  • thanks! didn't know it was possible to reference multiple selectors like that. – OzW Jul 26 '15 at 13:49