dropdown
by Soviut
HTML
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<p>
this is above this is above this is above this is above
</p>
<div class="move">
<div class="dropdown">
<div class="dropdown__trigger">Trigger</div>
<div class="dropdown__body">
this is some stuff this is some stuff this is some stuff this is some stuff
</div>
</div>
</div>
<p>
this is below this is below this is below this is below
</p>
CSS
.move {
margin-left: 100px;
}
.dropdown {
display: inline-block;
position: relative;
}
.dropdown__trigger {
display: inline-block;
background: cornflowerblue;
}
.dropdown__body {
display: none;
position: absolute;
min-width: 200px;
background: salmon;
}
.dropdown__body--visible {
display: block;
}
JavaScript
$(function() {
let visibleClass = 'dropdown__body--visible';
$('.dropdown__trigger').on('click', function() {
let body = $(this).next('.dropdown__body');
let stopDocumentClick = function(e) {
body.removeClass(visibleClass);
$(document).off('click', stopDocumentClick);
console.log('ding');
}
if (!body.hasClass(visibleClass)) {
body.addClass(visibleClass);
setTimeout(function() {
$(document).on('click', stopDocumentClick);
});
} else {
stopDocumentClick();
}
});
});