JrProgrammeur JrProgrammeur - 1 month ago 18
HTML Question

Hide cancels toggle

I try to hide the toggle if I click outside(somewhere else). But for some reason it will cancel the toggle if I use hide.

https://jsfiddle.net/vth9r5w6/3/

Can someone help me with this and explain to me why the hide cancels the toggle ?

HTML:

<td>
<input>
<img class="klik" style="cursor:pointer;" src="Afbeeldingen/favorieten.jpg">
<div class="clsFavorieten_From">111</div>
</td>

<td>
<input>
<img class="klik2" style="cursor:pointer;" src="Afbeeldingen/favorieten.jpg">
<div class="clsFavorieten_TO ">2222</div>
</td>


Script:

$(".klik").click(function(e){
e.preventDefault();
$(".clsFavorieten_From").toggle();
//e.stopPropagation();
});

$(".clsFavorieten").click(function(e){
e.preventDefault();
});

$(document).click(function(){
$(".clsFavorieten_From").hide();
});

$(".klik2").click(function(e){
e.preventDefault();
$(".clsFavorieten_To").toggle();
});

$(".clsFavorieten").click(function(e){
e.preventDefault();
});

$(document).click(function(){
$(".clsFavorieten_TO").hide();
});


EDIT:

Tried:

toggle- hide item when click outside of the div

Use jQuery to hide a DIV when the user clicks outside of it

and few more (can't find know)

sam sam
Answer

Use stopPropagation()

  1. event.preventDefault() – It stops the browsers default behaviour.
  2. event.stopPropagation() – It prevents the event from propagating (or "bubbling up") the DOM.

    $(".klik").click(function(e){
      $(".clsFavorieten_From").toggle();
      e.stopPropagation();

    });

    $(".klik2").click(function(e){
      $(".clsFavorieten_To").toggle();
      e.stopPropagation();

    });

    $(document).click(function(){
      $(".clsFavorieten_From").hide();
      $(".clsFavorieten_To").hide();
    });

Find the working code here: http://jsbin.com/wiyusisowu/