Javascript Boxes
Today I was trying to create a box on a web page that could be moved and resized. Well, several boxes, but that’s not important. I wanted a UI with handles indicating the places that the user can grab the box to resize in different directions, like this:
Given the position and size of the (blue) box at runtime, it’s not too hard to determine the green box positions, but you end up copying and pasting a lot of code if you do each one explicitly. So, I set out to write it as a loop, iterating once per (green) handle and avoiding duplication of code.
The key is to name the handles intelligently, and use the names to your advantage.
The following is a mix of javascript and comments where I avoided detail to describe my method. I’m doing this from memory, so there are bound to be errors…
var handle_list = ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'];
handles = {}; // object for the divs to live once they’re created
for (var i = 0; i < handle_list.length; i++) {
var name=handle_list[i];
handles[name]=document.createElement(’div’);
// perform some other formatting operations on the div here
if (name.indexof(’s’) != -1) {
// it’s on the south edge, so set the top offset to
// bluebox.top + bluebox.top - greenbox.size
} else if (name.indexof(’n') != -1) {
// it’s on the north edge so set top to be the same as
// bluebox
} else {
// set top to be halfway down
}if (name.indexof(’e') != -1) {
// it’s on the east edge, so set the left offset to
// bluebox.left + bluebox.width - greenbox.size
} else if (name.indexof(’w') != -1) {
// it’s on the west edge so set left to be the same as
// bluebox
} else {
// set top to be halfway across
}// Add the div to the document..
}
Granted, this could be made simpler, but I think it’s a pretty clever and usable method. Now, let’s say I want to have the correct mouse cursor display when the mouse is over the green boxes. This naming system works again:
handles[name].style.cursor = name + ‘-resize’;
0 comments
Kick things off by filling out the form below.
Leave a Comment