Reputation: 769
I have given the user the ability to generate their input onto the screen and also move each character around.
I don't want them to be able to move/place these characters anywhere though, I want to restrict the movement to a small square or rectangle.
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'));
});
});
Upvotes: 0
Views: 1632
Reputation: 3104
It looks like you can specify containment: http://api.jqueryui.com/draggable/#option-containment
I believe you can just change your initDraggable function:
function initDragable($elements) {
$elements.draggable({ containment: 'parent' });
}
A subsequent request asked about moving the vertical positioning of the characters: you can accomplish this be adjusting the styles for the characters and the character container:
.character {
width: 10px;
line-height: 100px;
font-size: 50px;
display: inline;
cursor: drag;
}
#word-container {
height: 100px;
border: 1px solid black;
}
I added a border around the container (so this feature can be easily seen) and added a height of 100px. I then set the line-height of the character to be 100px so it appears in the middle of the #word-container element. The user can now click and drag elements both vertically and horizontally within the #word-container element.
Upvotes: 2