My goal is to have selector B toggle when selector A is clicked or when clicking outside of selector B. This part is working fine.
However, I'm struggling with preventing selector B from toggling back unless selector A is specifically clicked - not when clicking outside of either selectors A or B.
$(document).ready(function() {
var Container = $(".redBar"); // Container (selector A)
function Toggle() {
Container.toggleClass("hide"); // Toggle Container with display none selector [to hide selector B]
}
// If selector B is visible
if ($(Container).is(":visible")) {
// On click of the document and selector A
$(document, ".toggleBar").on("click", function(event) {
// If the target of the click isn't selector A nor a descendant of selector A
if (!Container.is(event.target) && Container.has(event.target).length === 0) {
Toggle();
}
});
}
});
/* Selector A */
.toggleBar {
width: 150px;
color: blue;
text-transform: uppercase;
font-weight: bold;
}
.toggleBar:hover {
text-decoration: underline;
cursor: pointer;
}
/* Selector B */
.redBar {
width: 300px;
height: 50px;
color: white;
text-transform: uppercase;
font-weight: bold;
background-color: red;
}
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="redBarContainer">
<!-- selector A -->
<div class="toggleBar">toggle bar</div>
<!-- selector B -->
<div class="redBar"></div>
</div>