KyleHodgetts KyleHodgetts - 6 months ago 11
Javascript Question

How do i fade out a pop up box when the body behind it is clicked

Once my pop up box has faded in, i want it to fade away when the user clicks away from pop up box.

Currently, it fades in and then fades straight back out again.

Jquery

function jsRef(){
$('#footButton').click(function(){
$('#refPop').fadeIn(1000);
});

$('body').click(function(){
$('#refPop').fadeOut(1000);
});


HTML

<button id="footButton" onClick="jsRef()" type="button">References</button>


EDIT**
The file in question is sitting at the bottom of a main file via PHP include.
The pop up box should fade out when the body of the main file is clicked

Answer

Add e.stopPropagation() to the button click or add the body click event after you opened the popup.

Like:

$('#footButton').click(function(){
   $('#refPop').fadeIn(1000);

   $('body').click(function(){
       $('#refPop').fadeOut(1000);
   });
});

Or:

$('#footButton').click(function(e){
    e.stopPropagation()
    $('#refPop').fadeIn(1000);
});
$('body').click(function(){
    $('#refPop').fadeOut(1000);
});

I would definitely prefer the e.stopPropagation() solution. Also you dont need you function jsRef() in the onClick attribute of the button.