Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect which element is clicked

In briefly, I load a local HTML page into a div inside other web form in asp.net.

JQuery:

<script>
    $(function () {
        $("#includedContent").load("../HtmlHolder/index.html");
    });

</script>  

HTML:

  <div id="includedContent" class="WebHolder" style="width: 450px; height: 300px; border: 1px solid #808080; margin: 0px auto; overflow-y: scroll;"></div>

Now I want to get element's class name by click on them by below script:

<script>
    $(document).ready(function () {
        $('.WebHolder').on("click", "*", function (e) {

            alert("Class :" + $(this).attr("class"));
        });
    });
</script>  

My Problem is, when I click on any element, this code alert this Class name and it's Parent!

How to resolve it?

Note: element is not specific object, maybe it's an input or button or textarea or ... .

like image 763
Hamid Talebi Avatar asked Dec 19 '22 17:12

Hamid Talebi


2 Answers

You should use e.target(Use this as selector) not this(Because it is the parent)

alert("Class :" + $(e.target).attr("class"));

To avoid performing the action on parent: You can compare this and e.target to validate if it is the parent.

if( this !== e.target )

CODE SNIPPET FOR DEMO:

$('div').on('click', function(e){

    if( this !== e.target ) alert( 'Class is '+ $(e.target).attr('class') );

});
div{
  background: #fe7a15; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  
  I am the parent, Clicking me will not get you an alert but headers does, because they are my children.
  <br /><br />
  <h1 class="class-header-child-one">Header 1</h1>
  <h2 class="class-header-child-two">Header 2</h2>
  
</div>
like image 95
rmondesilva Avatar answered Feb 08 '23 14:02

rmondesilva


Use event.stopPropagation() in the event handler.

$('.WebHolder').on("click", "*", function (e) {

    alert("Class :" + $(this).attr("class"));
    e.stopPropagation();
});

This will prevent the event bubbling up the DOM tree.

Demo:

$(document.body).on('click', '*', function(e) {
    alert($(this).text());
    e.stopPropagation();
});
div {
  background: red;
}
div > div {
  background: orange;
}
div > div > div {
  background: yellow;
}
div > div > div > div {
  background: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Main
    <div>1
        <div>11</div>
        <div>12</div>
        <div>13
            <div>131</div>
        </div>
    </div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
</div>
like image 36
Tushar Avatar answered Feb 08 '23 14:02

Tushar