Dynamically set popup div position

I am looking for a solution on how to set the position of a popup div that is displayed by clicking on another div, but its position depends on where the position of the window is.

Here are 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 instance:

  • If the user clicks on the #opendiv to show the div #popupwith the scroll bar position of the browser window at the bottom, I want the #popupdiv to appear at the top of the #opendiv.

  • However, if the user clicks the div '#open' to show the div #popupwith the position of the browser window on top, I want the #popupdiv to appear at the bottom of the #opendiv.

Here is the script 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 css code with FIDDLE

+4
4

. . , - .

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
} 
+2

. "popupSection" .

$('.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);
});

: http://jsfiddle.net/epbdZ/2/

+1

"#open" event.offsetX event.offsetY, div, .

0

Source: https://habr.com/ru/post/1547921/


All Articles