I have a div expanding to fullscreen on click, and upon doing so a "close" button appears. On click of the close button, I want the div to return to its normal state and the button disappears. Why is the following code not working?
$("#SaveNClose").hide(); // Hide the close button
$('#myDiv').click(function(e) {
$(this).addClass('fullscreen');
$("#SaveNClose").show();
});
$(document).ready(function() {
$("#SaveNClose").click(function() {
$("#myDiv").removeClass("fullscreen");
$("#SaveNClose").hide();
});
});
#SaveNClose {
border: 1px solid black;
background-color: red;
border-radius: 50px;
padding-left: 10px;
padding-right: 10px;
padding-top: 5px;
padding-bottom: 5px;
}
.myDiv.fullscreen {
z-index: 9999;
width: 100%;
height: 100%;
position: fixed;
text-align: center;
align-items: center;
top: 0;
left: 0;
background-color: #799C4B;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myDiv" id="myDiv">
<button id="SaveNClose">× Click to Save and Close</button>
<div class="row">Main Text</div>
</div>
2
Answers
I’ve modified your code a little bit in order to separate the div which receives the click event and the div which renders full size.
The cause:
The "close" code is working, unfortunately it’s re-maximising (running the myDiv fullscreen) immediately after closing – so the appearance is that nothing happens.
A little bit of debugging shows what’s happening:
When you click the close, the close is inside myDiv so myDiv also gets that same click event as click events propagate up to parents.
The Fix
You need to stop the close event from propagating up to the parent div. There’s various ways to do this, the easiest is to add:
to the end of your event handler. Another is
event.stopPropagation()
– see jquery stopPropagationUpdated snippet with one line changed: