1

if I have the following:

$('body').on('click', function() {
  //alert($(this).attr('class')); alerts undefined because 'body' has no class
});

how can I get the specific element that was clicked on?

basically what I'm doing is, if anything on the body is clicked do one thing, but if its a specific element, do something else. so I'm checking the class, but that's not working

something like:

$('body').on('click', function() {
  if($(this).hasClass('specific') {
    //do specific();
  } else {
    //do generic();
  }
});
Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127
  • 1
    you need to look into **event delegation**. basically, what you want is `$('body').on("click","*",function(){//stuff...});` which says, if a child of `body` is clicked and matches selector `*` (anything) than do `//stuff...`. check out http://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on – chiliNUT Mar 04 '16 at 00:26
  • Possible duplicate: http://stackoverflow.com/questions/8945825/jquery-on-click-document-get-clicked-element – Hardy Mar 04 '16 at 00:27

2 Answers2

2

Use event.target

$("body").on("click", function(event) {
    alert(event.target);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>This is a paragraph</p>

<button>This is a button</button>

https://api.jquery.com/event.target/

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
0

My best suggestion would be to check the documentation here: http://api.jquery.com/category/events/

As you will see there are a few things you can do with a mouse click: http://api.jquery.com/category/events/mouse-events/

Without knowing what exactly you want to do; the advice given to you by Richard Hamilton above is probably the best.