Piotr Mirosz
Piotr Mirosz

Reputation: 866

Some equivalent to stop Propagation?

I have a issue...

I'm trying to get element ID using:

$('div').on('click',function(ev){
     ev.stopPropagation();
     checkEl = $(this).attr('id');
     if(checkEl != 'topics' && checkEl != 'exfillVal' ){
          $("#topics").hide();
     }
  })

But... it also block other elements with different event listener (click one's)... How can i achieve that?

$(function(){
var newHTML =[];
$('div').on('click',function(ev){
    ev.stopPropagation();
    checkEl = $(this).attr('id');
    if(checkEl != 'topics' && checkEl != 'exfillVal' ){
         $("#topics").hide();
         newHTML.push('<span class="reopen"  title="usuń">' + checkEl + '</span>');
    }
    $('#new').html(newHTML);
  })
  
  $('body').on('click', '.reopen',function(){ 
  $(this).hide();
  $("#topics").show();
  })
  
  // but that work
$('.reopen').on('click',function(){
  $(this).hide();
   $("#topics").show();
})


})
  
#main{
position:relative;
width:300px;
background-color:red;
}
div{
position:relative;
border:1px solid gray;
padding:15px;
width:100%:
}
#one{
background-color:black;
}
#two{
background-color:blue;
}#three{
background-color:orange;
}#four{
background-color:yellow;
}#fifth{
background-color:purple;
}
span{
padding:3px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<div id="one">
<div id="three">
<div id="four">
<div id="fifth">
</div>
</div>
</div>
</div>
<div id="topics">SOME COOL DATA </div>

</div>

<div id="new"></div>;

As you can see when i click on div with id "one,two,three,four,fifth,main" everything is working... but when append span element were clicked... Event listener aren't working correct, because append element schooled be hidden when click... instead of it just create another element.... where i make a issue?

Can i replace propagation with something else?

How i can rearrange a code?

Any help will be appreciate

Upvotes: 0

Views: 48

Answers (1)

trincot
trincot

Reputation: 350034

You could verify whether the handler is dealing with the original element or with a parent by comparing ev.target with ev.currentTarget. When they are the same then you know the click was really on that element, and it's not a parent you are looking at:

$('div').on('click',function(ev){
     checkEl = $(this).attr('id');
     if (ev.target === ev.currentTarget && checkEl != 'topics' && checkEl != 'exfillVal' ){
         $("#topics").hide();
     }
});

Upvotes: 1

Related Questions