Make the div a stick in the direction of another div

I am trying to make a div to jump to the right of another div using jQuery.

I based my decision on this answer using position:absolute and getting the position of the trigger element in jQuery and positioning the popover accordingly.

You can see the result of what I have on this JSFiddle I made: Result / Source .

The problem is that the popover div uses position:absolute , if I resize the page or the scroll bar appears / disappears - the popover becomes incorrectly aligned to the trigger.

How can I make the popover div stick to the right side of the trigger?

+4
source share
4 answers

Instead of relying on jQuery for this, you can make two elements glued together in CSS by making them inline elements, making them touch and setting the CSS container to white-space: nowrap .

HTML:

 <div id="main"> <p>If the draw is popped out, and you resize the page, it breaks, because it has position:absolute</p> <div id="clickable"> <div id="trigger"> <span>Click here - click away to hide</span> </div><div id="pop"> <span>Now Resize Page</span> </div> </div> </div> 

Please note that </div><div id="pop"> not a typo. To make inline elements touch, you need to remove all spaces in your markup.

CSS

 #main { width:300px; margin:50% auto; margin-top:0; margin-bottom:0; background-color:#EEE; padding:10px; } #clickable { white-space: nowrap; } #trigger { background-color: #FFF; width: 100%; border: 4px solid #ddd; display: inline-block; } #trigger span { margin: 5px; display: block; } #pop { background-color: #333; color: #EEE; height: 38px; opacity: 0; display: none; } #pop span { margin: 10px; display: block; } 

JS:

 $('#trigger').click(function(event) { event.stopPropagation(); var width = $(this).outerWidth(); var offset = $(this).offset(); var top = (offset.top+4)+'px'; var left = (offset.left+width)+'px'; $('#pop').css({ 'top' : top, 'left' : left, 'display' : 'inline-block', 'opacity' : 0, 'width' : 0 }).animate({ 'width' : '140px', 'opacity' : 1 }); }); $('html').click(function(event) { if (!($(event.target).closest('#pop').length)) { $('#pop').animate({'width':0,'opacity':0},500, function() { $(this).hide(); }); } }); 

Preview: http://jsfiddle.net/Wexcode/4kg2W/3/

+5
source

Place a div trigger with position: relative and a popover inside it with position: absolute, so the popover will have an absolute position, but always relative to the div trigger.

+3
source

You can adjust the location when resizing the browser:

 $(window).resize(function(){ $("#trigger").trigger('click'); }); 
+1
source

you can use the position property

 <div style="position: absolute;right:-10px ;top:0"></div> 
0
source

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


All Articles