Is there a way to confine a draggable object's movement to a specific area?

Users have been granted the ability to input their characters onto the screen and manipulate each character's position.

However, I only want users to move these characters within a specific square or rectangle area, limiting their placement options.

HTML

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js">
</script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>

<div id="word-container">
  <div class="character">P</div>
  <div class="character">l</div>
  <div class="character">a</div>
  <div class="character">c</div>
  <div class="character">e</div>
  <div class="character">m</div>
  <div class="character">a</div>
  <div class="character">r</div>
  <div class="character">k</div>
</div>
<br>
<br>

<form action="demo_form">
  Word:
  <input type="text" id="my-word" name="fname">
  <br>
  <button type="button" id="make-word">Make word</button>
</form>

CSS

.character {
  width: 10px;
  height: 15px;
  font-size: 50px;
  display: inline;
  cursor: drag;
}

JQuery

function initDragable($elements) {
  $elements.draggable();
}
initDragable($('.character'));

$(function(){
    $('#make-word').click(function() {
      var $this = $(this);
      var letters = $('#my-word').val().split('');
      letters = '<div class="character">'+letters.join('</div><div class="character">')+'</div>';
      initDragable($('#word-container').html(letters).find('.character'));
    });
});

Answer №1

If you're looking to define a specific containment area, check out this resource: http://api.jqueryui.com/draggable/#option-containment

To customize the draggable function, simply modify your initDraggable function as follows:

function initDragable($elements) {
  $elements.draggable({ containment: 'parent' });
}

A recent question inquired about adjusting the vertical positioning of characters. This can be achieved by tweaking the styles for both the characters and their container:

.character {
  width: 10px;
  line-height: 100px;
  font-size: 50px;
  display: inline;
  cursor: drag;
}

#word-container {
  height: 100px;
  border: 1px solid black;
}

I've added a visible border to the container and set its height to 100px for clarity. Additionally, I adjusted the line-height of the character to align it vertically within the #word-container. Users can now effortlessly drag elements inside the specified containment area in both vertical and horizontal directions.

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

Having trouble with JQuery on your Joomla 2.5 site?

Seeking assistance with implementing jQuery in my Joomla 2.5 website to switch between two images. While I have successfully achieved this on a static HTML page, I'm facing difficulties in Joomla. Here is the code snippet I am attempting to use within ...

Transfer various field values to jQuery

I am looking to send multiple field values to jQuery for validation, but currently only receiving the value of the changed field. How can I pass both field values to jQuery? Enter some text: <input type="text" name="txt1" value="Hello" onchange="myF ...

Understanding how to access both 'this' variables in TypeScript

When working in TypeScript, it's important to note that defining a function using () => {...} will make the this variable refer to the instance of the surrounding class. Conversely, using function () {...} will result in the this variable maintaini ...

Implementing a substantial update in MVC with the help of Slickgrid

Working on optimizing an MVC application that uses SlickGrid for grid edits. The grid can vary from 500 to 25,000 rows with around 40 columns. While the grid functions well, I'm facing challenges when it comes to posting changed data to my controller ...

get selection choice from the server

I have been trying to update my option select menu when the button is clicked without clearing out the menu. Currently, I am using $(#id).click(function(){}); but it seems that this approach is causing the select menu to clear out. Upon further investigati ...

Verify if a selection of days using momentjs exceeds 7 days

Is there a way to determine if more than 7 days have been selected on the calendar? I need to disable a button based on this condition. fromDate and toDate are global variables where I store dates from the calendar. Feeling a little confused at the moment ...

What is the correct way to markup the semantic form label assistance text?

When designing a form, there are certain form elements that may need explanatory text to clarify their function. One approach is to wrap this text in a paragraph element, as demonstrated below: label p { margin-top: -1px; font-size: smaller; } <div ...

"Unraveling nested data structures in React using JSON parsing

When attempting to fetch data in React from a MySQL database, I have encountered an issue where MySQL auto-escapes my values, including nested objects. While I am able to use the .json() function successfully on the top-level, I have run into problems when ...

Is jQuery(document) loaded on 'focus'?

Whenever a user clicks on an input, I intend to activate a method. The code I currently have is: jQuery(document).on('focus click', function(e){ console.log("focused on " + $(e.target).attr('id')); }); However, when I focus on ...

What is preventing me from loading a JavaScript script using a regular working URL?

After inserting the following line into my HTML file: <script type="text/javascript" src="http://static.citygridmedia.com/ads/scripts/v2/loader.js"></script> (whether inside or outside the <head></head> tags), I am encountering a ...

Mastering React state involves the skill of interpreting the updated state after making changes

I have a good grasp of JavaScript but I'm currently learning React. I decided to build a tic-tac-toe game and faced an issue with updating the game state properly. Specifically, I want the message to update immediately when there is a winner, the &apo ...

Utilize Ajax and Django to inject context into a template

I'm facing a challenge with displaying data from multiple sources in one view. My plan is to use Ajax, as loading 3 or 4 URLs simultaneously on page load is not feasible. Through the Django Rest Framework, I've managed to fetch the data and see ...

Having trouble rendering a private route screen in React, while all the other screens work perfectly

I am encountering an issue with my Private Route in React where it fails to render, while every other screen renders successfully. I have set up the Private Route to render my PrivateScreen.js component, everything seems to be set up correctly but I cannot ...

Leveraging ACE in conjunction with WT

UPDATE 3 Here is the finalized working code below. Remember to use ace.js from the src folder, as it will not work from the libs directory. You need the pre-packaged version from their site. WText *editor = new WText(root()); editor->setText("function( ...

What is the best way to incorporate tooltips in SVG?

My teacher wants me to display a tooltip on an SVG circle with links and information when we hover over it. They suggested using jQuery UI, but I've done extensive research and nothing has been able to assist me so far. ...

Having a floating left <UL> list with floating right text boxes positioned below the UL list instead of being set next to it

I'm attempting to align an unordered list on the left and a group of textboxes on the right within a div tag. The problem I'm facing is that the text boxes are positioned below the list items instead of being adjacent to them. .PersonLI { flo ...

Mastering AJAX requests in Zend Framework

I'm facing a challenge in integrating an AJAX search function with the Zend Framework. My Controller and Action look like this: class IndexController extends Zend_Controller_Action { public function indexSearchAction() { $this-> ...

Explore our interactive map and widget features that will seamlessly fill your browser window for a

Struggling to make a webpage with a Google Map, Chart, and Grid expand to fill the available space on the screen. Tried various CSS tricks but nothing seems to work. Check out this simplified example in JsFiddle that showcases the issue: http://jsfiddle. ...

Implementing event listeners with Angular UI-Router

Currently, I am working with Angular 1.4.5 and Angular Ui Router. I am facing an issue where I am trying to utilize addEventListener to execute a function when a text field is blurred. The challenge I am encountering is that during the load state, the elem ...

Updating and managing the CSS style for button states

In my asp.net application, I have 5 list items functioning as tabs on a Masterpage. When a user clicks on a tab, I want to redirect them to the corresponding page and visually indicate which tab is active by changing its class. What is the most effective ...