JQuery - Show Div1 on Div2 Click then Hide Div1 on Click

I have a simple problem. I am trying to show a video when a user clicks on a div. Then, when the user clicks anywhere on the page that is not in the video, hide that video. Completed millions of times but I can't find how to do it and other partial solutions on Stackoverflow have failed. Here's the complete code:

<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- CSS -->
<style>#videoDiv{display:none;}</style>

<!-- jQuery -->
<script>
$(function(){
    $(".clickForVideo").click(function(){
        $("#videoDiv").show();
    });
    $(document).click(function(event){
        if ($('#videoDiv').is(':visible')) {    
        /*  tried replacing above line with this line according to stackoverflow - also failed
        if(!$(event.target).closest('#videodiv').length) {  */
            $('#videoDiv').hide(); <!--Reference 1-->
        }
    });
});
</script></head>

<!-- HTML -->
<body>
<div id="videoDiv"><iframe src="https://www.youtube.com/embed/S28Zux62a_0">
</iframe></div>
<div class="clickForVideo">Click me to show video</div>
</body></html>

      

When I click on div.clickForVideo, no video appears. If I comment out the line labeled "Link 1" and then click .clickForVideo, the video / div appears, however does not disappear when the document is clicked as intended. How can I change the code or provide another solution for this problem. Many thanks. Andrew

+3


source to share


1 answer


This is because clickForVideo is also part of the document. And when you click it, the click event of the document (parent) is also called and it hides it again.

Try the following:



$(function(){
    $(".clickForVideo").click(function(event) {
        event.stopPropagation(); //<-----
        $("#videoDiv").show();
    });
    $(document).click(function(event){
        if ($('#videoDiv').is(':visible')) {
          if(!$(event.target).closest('#videodiv').length) {
            $('#videoDiv').hide();
          }
        }
    });
});

      

event.stopPropagation()

( Doc ) should stop the event bubbling to the parent iedocument

+1


source







All Articles