AndrewMk AndrewMk - 2 months ago 10
CSS Question

Child div affects parent div in css and triggers jquery method

I have parent div with class a "very-big-div" that nests another "container-div" that by its turn also nests another child divs. The very big div's made to act like a button and the div that come right after it is a container that appears when I click the very big div.

<div class="very-big">
<div class="container">
<!-- Some other more nested divs that has anchors and buttons -->
<div class="friend-request">
<div class="button-div">
<button class="accept">Trigger</button>
<button class="refuse">Trigger</button>
</div>
</div>

</div>
</div>


The problem is 2 things first: the css problem has not yet been solved

I assigned a hover pseudo class for the "very-big-div", and whenever I hover the "container-div" the hover properties(background-color) is applied to the "very-big-div". This is not what I intend to make, I want to only hover "very-big" div for the hover to apply.

.very-big{
background-color:green;
}


The second problem is : I have a jquery that deals with the container so it is toggled on/off by the "very-big-div"

$(document).ready(function(){
$("#container-div").hide();
$("#very-big-div").click(function(){
$("#container-div").toggle();
});
});


the container has both anchor and button tags whenever I click the an anchor or a button inside the container it is toggled to close itself, and that is not what I want, what I want is just when I only press the "very-big-div" the toggle is activated.

Answer

Same as @Jhecht has given the answer, I have just inherited his to mine.

You can stop propagation of the click of child element that trigger toggle by using target and excluding all the child elements of your .very-big container as:

$(".very-big").click(function(e) {
    var target = $(e.target);
    if (!target.is('.very-big *')) {
      $(".container").toggle();
    }
});

Code Snippet:

$(document).ready(function() {
  $(".container").hide();
  $(".very-big").click(function(e) {
    var target = $(e.target);
    if (!target.is('.very-big *')) {
      $(".container").toggle();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="very-big">
  Other Text
  <div class="container">
    This is text to fill stuff out so I can click on it.
  </div>
</div>