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

Ways to ensure that a function operates independently for each cloned div and not the original

I'm facing an issue where a jquery function needs to be executed when the drop-down is changed. However, the problem arises when I clone the div element and make changes in the drop-down of the newly cloned element, the effect takes place in the first ...

"Interactive functionality: Toggling checkboxes with a DIV click

I am trying to set up a simple div container that displays contact information in a formatted list (<ul><li>). Clicking on the div currently takes you to the user's profile page, which is functioning correctly. However, I am facing an iss ...

Modifying the DOM within a getJSON callback

My current challenge involves fetching data from the YouTube API and displaying it on my website. However, I am facing an issue where the DOM changes made inside the getJSON's callback function are not reflecting on the webpage. Even though I can see ...

Ensure the form is properly validated before initiating the submission process on 2checkout

Attempting to prevent the form from being submitted, I implemented the code below. Typically, this method works perfectly fine. However, when integrating 2checkout js (), it does not function as intended. <form onSubmit="validate(); return false;" meth ...

After transitioning to TypeScript, the CRA app is encountering issues loading CSS files compiled by SASS

My React application was originally created using create-react-app and I had been successfully loading scss files with the node-sass package. However, after deciding to switch to TypeScript following the steps outlined in , my css files are no longer being ...

Creating an IF statement within a jQuery / Ajax request when using PHP

Does anyone know how to implement an IF statement inside jQuery? I am currently working with two rows of data in a database that have different statuses. My main file for displaying the data is index.php. Here is a snippet from my index.php: $.get("tes ...

Using blending modes with gradient colors in an SVG design

I'm struggling to get my logo to change colors upon scrolling into a button with similar gradient colors, but I just can't seem to make it work. Can anyone lend me a hand? Thank you! Take a look at my Logo. I've attempted to add some styles ...

iOS 10's autofocus feature experiencing difficulties in focusing on input

While using an application on my desktop or Android device, I have noticed that the input focus works perfectly fine. However, when I try to run the same application on iOS 10 Safari, the input focus does not seem to be working. It is worth noting that I ...

undefined reference to $

I'm currently working on a JavaScript project that involves using key events to display alphabets on the screen. However, I've encountered an error and need some assistance. <!DOCTYPE html> <html lang="en"> <head> <met ...

I can't seem to figure out why this isn't functioning properly

Upon examining the script, you'll notice the interval() function at the very bottom. The issue arises from bc-(AEfficiency*100)/5; monz+((AEfficiency*100)/5)((AFluencyAProduct)/100); For some reason, "bc" and "monz" remain unchanged. Why is that so? T ...

Show special characters with accents within an SVG element on a webpage written in HTML

I'm having trouble with accented characters (like á, é, etc) not displaying in my SVG object on an HTML page. Here's how the page is declared: <!DOCTYPE html> <html lang="en"> <head runat="server"> <meta charset="utf-8 ...

The jQuery keyup event initiates multiple times, increasing exponentially with each trigger

I recently added a search bar with auto-complete functionality to my website. The search bar queries the database for elements that begin with the text entered by the user as they type. Although it works well, I noticed that every time the user inputs ano ...

Having trouble updating jQuery due to the inability to locate the suitable jquery.ui.core version

I am currently working on a MVC project using Visual Studio 2012. I recently performed an Updates package by going to tools > nuget package manager > manage nuget packages for solution > nuget.org > update all. The process seemed fine, but at the end, I en ...

CSS :hover problem, text appearing unexpectedly

I'm currently working on designing a logo that displays hidden text when hovered over, providing instructions to users. However, I've encountered an issue where the hidden text reveals itself even before the logo is hovered over. This is frustrat ...

Display XML elements on hover with a Bootstrap tooltip

I am attempting to showcase an XML snippet in my title attribute, similar to the example below. I understand that removing data-html="true" or changing it to false will resolve the issue. However, I also require a label in my title resembling the <stro ...

Enhance Your User Experience with Primefaces 6.0 Dialog Framework and Frameset

We are currently utilizing a combination of jsf 2.1, primefaces 6.0, and primefaces-extensions 6.0.0, along with mojarra 2.1.7 on weblogic 11g. This is our first time using primefaces 6.0, primarily because of the nested dialogs requirement. Upon opening ...

The scroll feature in JavaScript is malfunctioning

After countless hours of troubleshooting, I still can't figure out why the code snippet below is not working properly on my website at : <script> $(window).scroll(function () { if ($(window).scrollTop() > 400) { ...

Can a function be called when using ng-options with AngularJS select?

Here is some HTML code <select ng-model="selectedMarker" ng-options="shape.text for shape in Selects('shapes')"> </select> And below is the JavaScript code angular.module('todo', ['ionic']) . ...

Extracting information from a JSON file is a straightforward process that involves accessing

After spending months trying to extract data from a JSON file, here is what I have encountered: [["wrere","bogdan12",31,21,"profile_pic/poza3.jpg",78,21,31,"profile_pic/download.jpg"] , ["hey men","bogdan12",31,21,"profile_pic/poza3.jpg",76,21,31,"pro ...

How can I enhance the appearance of my custom field using CSS in Advanced Custom Fields?

Utilizing the Wordpress Advanced custom field plugin, I have successfully added a custom field to my site. Within this custom field, I have inserted images and now I am looking to center them on my page using CSS styles such as margin: 0 auto. If you&apo ...