Establish limits for draggable item

I am working on a project where I have a draggable element generated dynamically using jQuery. The div containing the element also has a background image. How can I ensure that the draggable element never goes outside of the boundaries of the div?

If you need to see the code, it can be found here: jsfiddle.net.

$(document).ready(function () {
    $("button").click(function () {
        $("#currentimage").append('<img id="dragable" src="http://s25.postimg.org/pi8ruls3z/image.jpg" width="200px" height="auto" />');
        $("#dragable").draggable();
    });
});

Answer №1

If you want to make the button clickable multiple times, you need to add containment: 'parent'. Make sure you use class dragable instead of id for uniqueness.

Here is a suggestion:

$(document).ready(function () {
    $("button").click(function () {
        $("#currentimage").append('<img class="dragable" src="http://s25.postimg.org/pi8ruls3z/image.jpg" width="200px" height="auto" />');
        $(".dragable").draggable({
            containment: 'parent' 
        });         
    });
});

Check out the DEMO here

Answer №2

Utilize containment to confine its container

containment: $('#currentimage')

Just so you know

An ID must be unique

.append('<img id="dragable"

Check out Two HTML elements with same id attribute: How bad is it really? for more information

You are adding multiple images with the same ID.


You can use a class instead

.append('<img class="dragable"

Then, utilize

$(".dragable").draggable();


Fiddle Demo

$(document).ready(function () {
    $("button").click(function () {
        var el = '<img src="http://s25.postimg.org/pi8ruls3z/image.jpg" width="200px" height="auto" />';
        $("#currentimage").append($(el).draggable({ containment: $("#currentimage") }));
    });
});

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

Explore and target elements using browser inspection

Is it possible to create a new CSS class using browser inspection that contains new hover/focus styles? For example: .CanIDo { /*some css rules (ex.)*/ width: 100; } /*my question (USING BROWSER INSPECTOR, not directly typing in the CSS file)*/ .CanI ...

What is the best way to make an input text the focus when an item on a dropdown menu is clicked?

I have a website with a dropdown menu and an input box. I want the user experience to be more seamless by automatically focusing the mouse cursor inside the input box when they click on an option in the dropdown menu. This way, users can start typing right ...

execute a function upon selecting a radio button

Below is the HTML code that includes two radio buttons. The default checked button is the "lease" option. <input id="quotation_request_payment_option_lease" class="choose_payment_option" name="quotation_request[payment_option]" type ...

Chrome browser not responding to jQuery .html refresh

I am facing an issue with a page containing a list of tasks, each with a dropdown menu featuring a list of teams to which the task can be assigned. However, pre-populating the dropdown in the Action function is not feasible due to the large number of tasks ...

Sending a parameter from a click event to a function

Struggling with a jQuery and AJAX issue all night. I am new to both and trying to implement something similar to this example. I have an edit button with the ID stored in a data-ID attribute. Here's an example of what my button looks like: <butto ...

Utilizing jQuery to send AJAX requests and display the results on separate lines within a textarea

My form includes a text area where users can enter keywords, one per line. I would like to implement the following functionality: upon clicking a button, an ajax request will be sent to the server to retrieve the result for each keyword entered. The resul ...

Designing a captivating loading screen in Sencha Touch optimized for various mobile device resolutions

I am currently working with Sencha Touch 1.1 and I need my application to be compatible across various mobile platforms such as Android, iPhone, iPad, and Blackberry. One of the requirements is to have a splash screen at startup, which I have tried impleme ...

Unexpectedly, the jQuery ajax post request has stopped functioning

I encountered a problem with a jQuery ajax call in my ZF2 application. It was functioning properly until it suddenly stopped working. Even when I purposely input a non-existent action in the request, it no longer triggers a server error as it did before. I ...

Conceal Bootstrap 3 tooltip

There's a tooltip attached to a button within a bootstrap dropdown. Whenever I click that button, the original button is hidden and another button is displayed. However, the tooltip from the previous button remains visible until I scroll vertically or ...

Ensuring scroll position remains fixed post screen rotation in HTML/Javascript

Is there a foolproof method to retain the scroll position in an HTML document following a screen rotation? While this issue is specifically in a Cocoa Touch UIWebView, it seems to be prevalent across different platforms. The standard practice appears to re ...

Unable to retrieve JSON using the getJson method

I've been transitioning to using jQuery exclusively, but I can't seem to get this function to work. My JSON file is pretty simple: { "status": "active" } All I'm trying to do is check if something has switched on or off. I created a basic ...

AlphaVantage Platform: Element not found

As someone new to API services, I'm currently working on constructing a dashboard that pulls data from the Alphavantage API. My goal is to retrieve data for 3 symbols simultaneously by creating a list and passing the index to my API call. Each symbol ...

I am facing an issue with submitting a form using jQuery POST and php serialization

I am struggling to send form data using jQuery. The data seems to be stuck in a loop where it keeps requesting the page ./?page=game&mode=search&type=private with the GET function and does not reach the server. Can someone help me identify what I m ...

The Angular JS field will only be considered valid if its value is more than zero

I have a text box in my form that changes its value dynamically when a user selects a category from a dropdown menu. Initially, the value is set to 0. $scope.validCats = "0"; HTML: <input ng-model="validCats" value="" type="text" class="form-control ...

Having trouble with Floating Labels in Bootstrap 5

Having trouble with my floating labels - any advice? https://i.sstatic.net/fk0CG.png Here is the code snippet: <div class="form-floating mb-3"> <input type="text" class="form-control" autofocus id="txtNome" placeholder=" "> <la ...

When data is submitted through the POST method, it mysteriously disappears

When I send the "user" variable to another page called Survey.php, here's how it looks: In the index.html file: <form action="Survey.php" method="post" name="frm"> <div><input type="text" name= ...

How come the focus doesn't work when altering the CSS code simultaneously?

My attempt at creating a user interface involved an issue where the input field was not visible initially. After clicking the button, the input would appear on the screen, and I wanted to automatically focus on it. This is what I tried to achieve: Initial ...

An AJAX script for dynamically adding, modifying, and removing records from a database

How can I implement a functionality where by pressing "-" the vote is removed from the database, and when any other number is selected, the vote will be updated in the database with that value? The default value of the dropdown list is votacion.votCalific ...

Overriding Divs with Navigation

In my WordPress blog, the top menu consists of 3 divs: one for navigation, one for social icons, and one for the search bar. Unfortunately, the navigation div is currently overriding the other two divs, causing them to lose their functionality. When I ad ...

Issues with Opera displaying specific characters when using webfonts

Perhaps it's not supposed to work this way, but hear me out. I'm utilizing Google Web Fonts and adding the PT Sans font like this: <link href="https://fonts.googleapis.com/css?family=PT+Sans:regular,italic,bold,bolditalic" rel="stylesheet" ty ...