Discover a new method for mastering jQuery Draggable: an advanced technique

Click here for the interactive demo.

I'm trying to create a draggable effect for the cover element within the pic-area, but I only want it to be draggable until it completely fills the space without any white gaps. Please have a look at the example below:

#pic-area{
    overflow:hidden;
    height:150px;
    width:500px;
    border:2px solid #000;

}

UPDATE: Issue Resolved!

$(document).ready(function(){

$("#cover").draggable({

    stop: function(ev, ui) {
        var hel = ui.helper, pos = ui.position;
        //horizontal
        var h = -(hel.outerHeight() - $(hel).parent().outerHeight());
        if (pos.top >= 0) {
            hel.css({ top: 0 });
        } else if (pos.top <= h) {
            hel.css({ top: h });
        }
        // vertical
        var v = -(hel.outerWidth() - $(hel).parent().outerWidth());
        if (pos.left >= 0) {
            hel.css({ left: 0 });
        } else if (pos.left <= v) {
            hel.css({ left: v });
        }
    }
 });

});

For a working example, please see this link

UPDATE2

Alternatively, you can try this version as well.

var topX = $('#pic-area').outerWidth() - $('#cover').width() + ($('#pic-area').offset().left*2);
var topY = $('#pic-area').outerHeight() - $('#cover').height() + ($('#pic-area').offset().top*2);
$('#cover').draggable({
    containment: [topX, topY, 0, 0]
});

Answer №1

$(document).ready(function(){

$("#cover").draggable({

    stop: function(ev, ui) {
        var hel = ui.helper, pos = ui.position;
        //handling horizontal movement
        var h = -(hel.outerHeight() - $(hel).parent().outerHeight());
        if (pos.top >= 0) {
            hel.css({ top: 0 });
        } else if (pos.top <= h) {
            hel.css({ top: h });
        }
        //handling vertical movement
        var v = -(hel.outerWidth() - $(hel).parent().outerWidth());
        if (pos.left >= 0) {
            hel.css({ left: 0 });
        } else if (pos.left <= v) {
            hel.css({ left: v });
        }
    }
 });

});

Solution implemented successfully! Check out the working example here

UPDATE2:

Different approach available here

var topX = $('#pic-area').outerWidth() - $('#cover').width() + ($('#pic-area').offset().left*2);
var topY = $('#pic-area').outerHeight() - $('#cover').height() + ($('#pic-area').offset().top*2);
$('#cover').draggable({
    containment: [topX, topY, 0, 0]
});

Answer №2

Make sure to incorporate jqueryUI into your project. You can find the cdn link here:

Although it may not be perfect, including this should resolve the issue you are experiencing.

I have made some modifications to your code to demonstrate that it functions correctly:

http://jsfiddle.net/jonigiuro/e93Z5/3/

#pic-area{
    overflow:hidden;
    height:800px;
    width:800px;
    border:2px solid #000;
}

Check on the left side of the page under "External Resources" to see that I have included jquery UI

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with jQuery AJAX error callback not triggering upon encountering an error

I'm currently facing an issue with implementing the management of an HTTP 413: Request entity too large error from my server. I've made the following attempt to address it: $.ajax({ url: "submit.php", data: { "data": POSTData ...

Remove identical options from the dropdown menu

After hard-coding and adding items to the dropdown list for team size, such as 1, 2, 3, I am encountering an issue when loading it for editing or updating. Duplicate values are appearing in the list: 1 1 2 3 4... How can I remove these duplicate value ...

What is the method for eliminating the box shadow on a table?

Seeking assistance on removing the shadow effect from ng-tables upon hovering. Can someone guide me on how to achieve this? See screenshot here: http://prntscr.com/jcpl5g widget-body { background-color: #fbfbfb; -webkit-box-shadow: 1px 0 10px 1px rgba(0, ...

Displaying dynamic data in a Bootstrap modal using Laravel

I have implemented a bootstrap modal in my dashboard. The button that triggers the modal is placed on another page where I extend the dashboard layout. When I click on a button with a different product ID, I want the modal to display information related ...

The mouse coordinates do not align with the drawing of a rectangle on the canvas

I am having some issues with drawing a rectangle on mouse drag over the canvas that is overlayed on an HTML5 video JS player. The rectangle is being drawn, but it does not align correctly with the mouse coordinates. I suspect that the canvas, which is ove ...

Fading effect of Bootstrap JS on reducing content size

My quest for a toggle collapse button led me to this helpful link: https://getbootstrap.com/docs/4.0/components/collapse/ I found what I needed, but encountered an issue with the transition; clicking on the button immediately reveals my div. I desire a slo ...

What is the best method for excluding past dates in the Ui calendar?

As a beginner with Ui calendar, I am seeking guidance on how to prevent users from selecting or interacting with previous dates in Ui-calendar using angularjs. While the Eventdrop, EventResize, and eventclick features are functioning properly for me, it ...

Arrangement of elements with no space at the top

Does the position.top of an element with a top-margin set to a value larger than 0 get calculated from the top-left point of the element or its margin when retrieving its position? ...

Calculate the percentage of a specific side for the border-radius using a single radius

I am looking to adjust the border-radius of a div based on its dimensions without creating an elliptical or pill shape effect. For instance, if a div has a width and height of 250px and 35px respectively, the border-radius should be set to 7px. Similarly, ...

Intersection Observer API is not compatible with the functionality of the navigation bar

Having trouble with the Intersection Observer API. Attempting to use it to show a nav-bar with a white background fixed to the viewport once it scrolls out of view. Initially tested using console.log('visible') successfully to determine visibili ...

Data not displaying in selected option after selection

I'm having an issue retrieving the list of "states" once I choose a "country". The country list displays correctly, but upon selecting a country, the states do not appear in the dropdown selection. I am using ajax to send data to ajaxData.php from i ...

The full width of the div exceeds the parent's width, resulting in the box size being ineffective

I'm experiencing an issue where my cover is wider than my element and content. It seems to be covering the gunter, but I've tried using background-clip: content-box; and box-sizing: border-box;, which haven't resolved the problem. I also wan ...

Issue with PHP causing Jquery alert to trigger twice rather than once

I am currently working with jQuery and PHP. I have a button labeled "Edit" but whenever I click on it, the alert message pops up twice instead of just once. Below is my HTML code within the PHP tags: <?php $PostComment2='<div class="button1 ...

Make the Angular Modal scrollable except for when a specific div is being click dragged

I am working on an Ionic app that uses AngularJS. One issue I encountered is with a modal popup that can sometimes extend beyond the visible area. To address this, we applied overflow: hidden to its CSS class. However, there is a specific functionality i ...

Struggling with adding two-digit numbers in a JavaScript calculator

While I can add single digits with no problem, adding double digits proves to be a bit tricky. The split method in this if statement is useful for isolating individual numbers, but it struggles when dealing with double digit numbers. if(e.value == '= ...

Best Practices and Tips for Layout Design Using HTML and CSS Grid

As I begin my journey into front-end development, I am currently immersing myself in studying html, css, and vanilla javascript. While things are going well so far, I find myself struggling with understanding the organization of design layouts in general. ...

CSS causing black bars to appear when image is moved

I recently started working with HTML/CSS and JS, but I've encountered a small issue. I'm using the bootstrap carousel and it's functioning well, but when I try to move the image higher up, black bars appear at the bottom as if my images are ...

Modifying the header on an HTML page

Looking for assistance with code to have my site header appear after the page has scrolled past Figure 1 and change on reaching Figure 2. Any suggestions on how I should write this code? Your help is greatly appreciated! ...

Transmitting Data to PHP Using JQuery/AJAX

I'm struggling with this issue. Here is the HTML code that I have: <input type="text" class="studno"><input type="button" value="Check" class="chstudno"> How can I send this data to PHP using JQuery/AJAX? Below is the code that I current ...

Adding a three-dimensional perspective to an HTML5 canvas without utilizing CSS3 or WebGL

Here is a canvas I am working with: http://jsbin.com/soserubafe Here is the JavaScript code associated with it: var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var w = canvas.width; var h = canvas.height; var cw=canvas. ...