I am looking for a solution on how to set the position of the pop up div which is showed by click on an another div but its position depends on where the position of the window is.
Here some examples of my divs:
<div id="header"></div>
<div id="open">Click here to open the popup</div>
<div id="popup">
<div class="popup-wrapper">
<div class="content">
<h1>TEST</h1>
</div>
</div>
</div>
<div id="footer"></div>
For example:
If the user clicks the #open
div to show the #popup
div with the position of the browser's window scroll bar in the bottom, I want that #popup
div to show at the top of the #open
div.
However, if the user clicks the '#open' div to show the #popup
div with the position of the browser's window on the top, I want that #popup
div to show at the bottom of the #open
div.
Here is the script that I used:
$("#popup").click(function(e) {
if ($(e.target).closest(".content" /*or any other selector here*/).length > 0){
return false;
}
$("#popup").fadeOut(200);
$("body").addClass("no-scroll");
});
//This is just to open the popup
$('#open').click(function() {
$("#popup").show();
});
Here is the complete code with css FIDDLE
Check the user's scroll bar position. Then display your popup depending on the scroll bar's position. Haven't tested the code below but something similar to this.
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
if(scrollTop == 0){
// Window on top. Display popup
}
if(scrollTop == $(window).height()){
// Window on bottom. Display popup
}
Here is a more dynamic working solution. It looks for any element with the class of 'popupSection' and opens the popup on it.
$('.popupSection').on('click',function(e){
var target = $(e.target);
var targetOffset = target.offset().top;
var scrollPosition = $(window).scrollTop();
if ( scrollPosition <= targetOffset ) {
openPopup(targetOffset);
} else {
var targetHeight = target.height();
var contentHeight = $('#popup .content').outerHeight();
var targetBottomOffset = targetOffset + targetHeight - contentHeight;
openPopup(targetBottomOffset);
}
});
var openPopup = function(offset){
var popup = $('#popup');
var popupContent = $('#popup .content');
if ( popup.css('display') === 'none' ) {
popup.css('display','block');
}
popupContent.css('top',offset);
}
$("#popup").click(function(e) {
$("#popup").fadeOut(200);
});
Working fiddle: http://jsfiddle.net/epbdZ/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With