glenelkins Posted January 28, 2008 Share Posted January 28, 2008 Hi I have written the following code ( still needs a few revisions ) to enable any element on a page to become dragable. All elements have to be absolutely positioned for this to work. My question is, if i place the elements inside an outer container, is there a simple way to stop them being dropped anywhere appart from the container elements? Without having to write code to test its new position? I know i can get the parent container info if needed.. // Global vars var _dragging = false; var _e_object; var _event; // Events document.onmousedown = MouseDown; document.onmousemove = MouseMove; document.onmouseup = MouseUp; function MouseDown() { // Get the window event _event = window.event; var node; // Detect which element was clicked if ( _event.target ) { node = _event.target; } else { node = _event.srcElement; } // Check that what we clicked was in fact a DIV element if ( node.nodeName == "DIV" ) { // Create element object _e_object = document.getElementById ( node.id ); // Set the dragging var _dragging = true; } } function MouseMove() { if ( _dragging == true ) { // Create the event object ( AGAIN?? ) _event = window.event; // Get the mouse position if ( _event.clientX && _event.clientY ) { var mouse_x = _event.clientX; var mouse_y = _event.clientY; } else { var mouse_x = _event.pageX; var mouse_y = _event.pageY; } // We need the width and height of the box // to position the mouse in the middle var element_width = remove_px ( _e_object.style.width ) / 2; var element_height = remove_px ( _e_object.style.height ) / 2; // Change mouse _e_object.style.cursor = "hand"; //Bring to front _e_object.style.zIndex = 10000; // Position the element to the mouse _e_object.style.left = mouse_x - element_width; _e_object.style.top = mouse_y - element_height; } } function remove_px ( the_string ) { var string_array = the_string.split ( "p" ); return string_array[0]; } function MouseUp() { if ( remove_px ( _e_object.style.left ) > 0 && remove_px ( _e_object.style.top ) > 0 ) { // Set dragging to false _dragging = false; } } function show_debug ( message ) { document.getElementById ( "debug" ).innerHTML += "<br>" + message; } Quote Link to comment Share on other sites More sharing options...
glenelkins Posted January 28, 2008 Author Share Posted January 28, 2008 also if it makes life easier... how can you detect which element another was dropped on? Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.