Satch3000 Satch3000 - 7 months ago 49
Javascript Question

Javascript self hide parent div not hiding when span clicked

I have a div that's been created dynamically. Multiple of them are created and I need to do a self parent hide, so this is what I've done:

This Div:

<div><a href="">'+inputText+'-</a><div class="box"></div><span onclick="dismiss();">Close</span></div>


The Function:

function dismiss() {
$(this).parents('div').fadeOut();
}


It's not hidding when I click the close span.

Answer

Inside dismiss function this refers to window object, instead pass the this as an argument .

function dismiss(ele) {
  $(ele).parents('div').fadeOut();
  console.log(this);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div><a href="">'+inputText+'-</a>
  <div class="box"></div><span onclick="dismiss.bind(this);dismiss(this);">Close</span>
</div>