I need to be able to create a popup that is mouse/touch draggable. It needs to be prevented from being able to be moved out of the viewport. I've tried for hours. I'm hoping somebody knows of existing code or knows how to do it. Help would be appreciated.
ypkush: Thanks but no, that's a drag function. I need something that will make the element follow the mouse, not a drag. When I mouseup the element needs to stop where ever it is, not a drop. Also, when the mouse runs out of the viewport the element needs to recognize that as a mouse up and not take the element out of the viewport.
This may help for you, here is the example https://codepen.io/lfry/pen/AEqKRM https://www.kirupa.com/canvas/follow_mouse_cursor.htm
ypkush: Thanks again for your response. Still, this isn't quite it. I did learn of this function from it: requestAnimationFrame which I believe I can use. I can make an element follow a mouse and I can make it stop and stay on mouseup (not a drop). BUT when the mouse goes out of the viewport the element flips out. I want it to follow a page scroll but when the mouse is out of the viewport and off the page the element should just stop. I'm hoping requestAnimationFrame will help with the page scroll problems at least and that *may* solve the whole problem. Again, thanks for your help.
Try these: https://jsfiddle.net/nagaraju_agan/b12aLu87/ https://jsfiddle.net/lesson8/SYwba/ https://jsfiddle.net/ydchauh/4cbk0sq5/ https://stackoverflow.com/questions/7143806/make-an-image-follow-mouse-pointer When I need a code, I search: jsfiddle blah blah or stackoverflow blah blah
Try this: <div id="popup" class="draggable"> <h2>Draggable Popup</h2> <p>This is a draggable popup. Try moving it around!</p> </div> HTML: #popup { position: absolute; top: 50px; left: 50px; background: #fff; border: 1px solid #000; padding: 10px; } .draggable { cursor: move; } Code (CSS): $(document).ready(function() { var isDragging = false; // Get the initial position of the popup var posX = 0; var posY = 0; var popup = $('#popup'); popup.mousedown(function(e) { isDragging = true; posX = e.clientX - popup.position().left; posY = e.clientY - popup.position().top; }); $(document).mousemove(function(e) { if(isDragging) { // Calculate the new position of the popup var newPosX = e.clientX - posX; var newPosY = e.clientY - posY; // Constrain the position within the viewport newPosX = Math.min(Math.max(newPosX, 0), $(window).width() - popup.outerWidth()); newPosY = Math.min(Math.max(newPosY, 0), $(window).height() - popup.outerHeight()); // Set the new position of the popup popup.css({top: newPosY, left: newPosX}); } }); $(document).mouseup(function() { isDragging = false; }); }); Code (JavaScript): This code will create a draggable popup that can be moved within the viewport and will be confined within the bounds of the viewport. Just make sure to include jQuery before the JavaScript code if you're using jQuery.