Knowing which element triggered the event

Asked

Viewed 67 times

0

Hello,

I can tell inside some_function which class triggered the event click (.Class1 or . class2)?

$('.class1, .class2').click(some_function);

Thank you.

  • What if the element has this way? <button type="button" class="Class1 class2">?

3 answers

4


Can use $(this).hasClass("class1").

The $(this) takes the element that triggered the event, and the hasClass checks which class it has.

$('.class1, .class2').click(function() {
  var class1 = $(this).hasClass("class1");
  var class2 = $(this).hasClass("class2");
  
  console.log("Foi class1=" + class1);
  console.log("Foi class2=" + class2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  <button class="class1">Class 1</button>
</p>
<p>
  <button class="class2">Class 2</button>
</p>

  • Thanks! It is possible to do the same by id (#id) ?

  • you say you know if an element with a specific id has a certain class? if it is yes

4

It is possible to know which classes of the element triggered the event yes. You can use this inside that function, which will be the element clicked, and then know the classes of that element or compare if the element has a specific class.

Example:

$('.class1, .class2').click(some_function);


function some_function() {
  const todasAsClasses = this.className;
  const temClasse1 = this.classList.contains('class1');
  const temClasse2 = this.classList.contains('class2');
  console.log(todasAsClasses, temClasse1, temClasse2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="class1">
  Btn 1
</button>
<button type="button" class="class2">
  Btn 2
</button>

  • E se o elemento tiver desta forma: <button type="button" class="class1 class2">?. At first, I figured he wanted to know was this way, I thought it was complicated to know what the class would be.

  • @Taffarelxavier in this case my example gives true true for both classes, you would have to check both.

  • How to do it, specifically in this case? I believe it is not possible.

  • @Taffarelxavier In that case just do if (temClasse1 && temClasse2) { faz algo específico para quando tem as 2 classes } - and then you treat it the way you think best (which was not specified in the question what is to do)

3

Very simple form:

$('.class1, .class2, .class3').click(function(ev){
     console.log(ev.target.className + " disparou o evento");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  <button class="class1">Class 1</button>
</p>
<p>
  <button class="class2">Class 2</button>
</p>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.