Simple JavaScript drag and drop witout the help of a library - javascript

I am simply looking for a way of using drag and drop without jquery or any other library. If a dragged object is dropped on another element the later element should start an event (in FF - better would be browser independent).
I know that drag and drop for JavaScript was discussed sometimes before but the previous postings didn't help me.
Although I found some examples it is not clear to me if there is a "drop" or "dragdrop" events exist but these things don't work:
<p ondrop='alert("It worked");'>Text</p>
<p ondragdrop='alert("It worked");'>Text</p>
How could this be done?
Many thanks in advance.

I agree with the other answers. A library will save you a lot of time and headache. This is coming from someone who just recently created a drag-and-drop control from scratch.
If you insist though this is what you'll need to do:
Bind a onmousedown event to the div you want to drag (div.onmousedown).
Change the div's position style to absolute (div.style.position = 'absolute')
Begin capturing mouse movement (document.onmousemove).
On mouse move update the div's position (div.style.top|left = '[location]px')
On the div's onmouseup event (or the document's) unbind all the handlers and do any other cleanup (null out position changes, etc).
Some problems a library will probably solve:
While dragging you will select text on the page (looks ugly).
Binding to events is different between browsers.
You have to calculate the size of the element being dragged if you want to show placeholders and to make it not "pop" when you begin dragging the control (since changing to absolute positioning will remove the element from flow).
You will probably want your dragged element to move fluidly so you will have to store some mouse offset when selecting the element or automatically center the element to the mouse.
If you want to drag an item in a list you'll have to write a ton more custom code for that list to accept the dragged item.
You'll have to take into consideration dragging when the window is scrolled and possibly dragging inside other elements that are positioned strangely.

I am simply looking for a way of using drag and drop without jquery or any other library.
I'm sorry, but there are no such thing as simply drag and drop without any library. You can write it all yourself, but that will be a lot of JS to make it work in all browsers.

Hmm. It's probably not that simple that you'd want to do it yourself, but I would look at Peter Michaux's FORK Javascript drag and drop library -- unlike JQuery or all those big libraries, FORK's modules are decoupled from each other, and are simple enough that you could probably look at Peter's source code and figure out the bits you need. (edit: I'd just use FORK.Drag as it's really small: 7.6KB total minified)

While I agree that library is the way to go, the answer you want is onmousedown, onmousemove, onmouseup. You have to handle those three events.
In onmousedown you'd find the target (event.target or similar in different browsers) and set draggedObject = event.target. You'd also start handling the onmousemove event.
Whenever the onmousemove event fired, you'd move the dragged element based on the difference in position since last time the onmousemove event fired.
In the onmouseup event, you'd clear your draggedObject variable and stop handling onmousemove.
It's not very crossbrowser, but it's the core of what you'd need to do for dragging and dropping.

Related

how do I recreate the sencha style gesture scroll for lists and content?

So... I am working on an interaction design project and I want to create a sencha-style gesture scroll for content areas. The way I've done it so far, is to attach touchmove/start/end events to the content area, and it translateY's the contents. It works in on desktop with mousemove/up/down events, but it jumps around like crazy with touch. I'm not sure whats wrong.. here is a link to a prototype.
**requires webkit.
http://apps.omorphos.com/gesture-scroll
I think it is an issue with the event response, but I tried and haven't been able to nail it down. Any help is greatly appreciated!
So, I figured this out.
What I was doing was attaching the touch event to the list tag itself.. and, that works fine on desktop with mouse events; however, with touch, the target changes and touchend doesn't fire properly.
So, what I did, and what I believe sencha does, ... and I had originally implemented but went in a different direction... is have an absolutely positioned element with a transparent background color floating above the element that will be manipulated. All of the touch events will be captured by that DIV and then the elements below can be manipulated without losing the event data.
In the new version I used HammerJs ... more info: http://eightmedia.github.io/hammer.js/
but i'm pretty sure you could just use standard events; but the good thing about hammer js, is that it will translate touch events to mouse events for testing in the browser, this also means making the coordinates for touch the same as mouse, so you can access mouse event coords via
e.gesture.touches[0].pageX
e.gesture.touches[0].pageY
which let's you write less code.
Part 2:
Additionally... part of the issue is... how do you click on the content/components(e.g. links) below the screen.
How you do this... is you take the coords from the event handler and pass them through this native Javascript function...
var a = document.elementFromPoint(x, y);
this will return the dom element. and all you have to do is trigger the click/tap event.
Which would be great, except it will pick the element with the highest z-index.. so that is your screen obj(the one that is capturing all of the touch events). So, what you need to do, is hide the screen after a tap is registered, and then execute this function 200ms later, and then bring back the screen to capture whatever events.
You can do this with this function...
$(theScreen).on('tap', function(e){
screen.hide();
var hit = document.elementFromPoint(e.gesture.touches[0].pageX, e.gesture.touches[0].pageY);
$(hit)[0].tagName !=="A" || $(hit).trigger('click');
setTimeout(function(){screen.show()},300);
});
And, that is how I solved it!
My code is not super annotated, but you can find it at the link below:
Updated example:
http://apps.omorphos.com/gesture-scroll/v2/

jQuery Hover Over Image Content Only and Not Alpha

Perhaps the title isn't great, but I had a little trouble with the wording...
Basically, is it possible to have jQuery's hover only fire over the actual content of a png with an alpha channel.
So in the image below;
http://i.imgur.com/3kO7v.png
Only fire on the rectangle and not the alpha channel which make up the rest of the document bounds...
I've tried the obvious $('obj').hover(function(){stuff}) but this fires on the alpha channel too...
The final implementation of this will be for more complex shapes than just a rotated square, so css3 tricks are out for the primary basis, but could be used with a back-up/shim, plus I need to support IE7 and ipad,iphone,ipod....
If there is a CSS2 solution then that would be suitable too. Also any real guidance on this issue is more than welcome.
My backup for this will be to have an empty div, display block and position it over the shape and then use that. This will obviously not be ideal for the less square objects.
Any hits or tips are more than welcome.
Thank you
Yes it is possible depending on the stacking context of your elements. Keep in mind that when you do a focus over any particular element on a page, that you are actually focusing all other elements within the same stacking context.
So what you could do is either stop the event from bubbling up the stack (if the element you want to "hover" is lower in the stack that the elements you want to prevent hover effects on), or specifically put in prevent default for onhover events for all elements in the stacking context except for the one you want to actually get a hover effect.

Trigger onMouseOver when mouse pointer already is over after page load

I have several pages that are all very similar. They have some javascript rollover links (images are preloaded, then there is a onMouseOver event that calls an image swap function and finally, there is a onMouseOut event that restores the original image).
When the user clicks on a rollover link that points to another page that has a rollover link on the exact same position, the image on the new page would be expected to load on the "over" state. This is not the case in Chrome and Safari (IE and Firefox work as expected).
So... On page load, is there a way to check if the mouse is already hovering the image to swap it right away? Something like "OnMouseAlreadyOver"?
Thank you.
If you using jQuery, it works without any problems!
http://jsfiddle.net/beuae
(not only for buttons, for divs also)
Actually, jQuery is a very good framework which assures everything goes as you expect, and cross-browser. This example confirms it.
The W3C standard says
onmouseover = script [CT]
The onmouseover event occurs when the pointing device is moved onto an element. This attribute may be used with most elements.
onmousemove = script [CT]
The onmousemove event occurs when the pointing device is moved while it is over an element. This attribute may be used with most elements.
mouseover is fired on moving over the boundary of the object. mousemove happens when the mouse is already over the element.
You may need to use onmousemove (or even both).
You may need to actually do the calculation based on the element position and the mouse cursor position.
//Get Mouse Position
document.onmousemove=getMouseCoordinates;
function getMouseCoordinates(event){
ev = event || window.event;
mouseX = ev.pageX;
mouseY = ev.pageY;
}
You can't without passing a variable to the other page or using cookies to track which was hovered (and that will fail over if people do change their mouse position)
In theory you could check the mouse position and the button position however there is no way to get the mouse position unless an event is triggered, so the mouse has to move and if it move the CSS :hover should get triggered.
It's a minor issue tho, I doubt most people are going to click a link, wait for the next page and then expect that link to be hovered and ready to click again (why wouldn't anyone one to keep clicking the same button unless it does different things)
From a UX point of view I wonder if webkit doesn't have the best approach here, why port the action of one page to another.
You can use document.getElementFromPoint(mouseX, mouseY) to get the element, but the only way to get the cursor's position is via an event. The problem is, the only events are clicks and mouse movements, which require user input from the beginning, which is what you're trying to avoid.
In short, no, it's not possible to do with JavaScript. You're left with using CSS.

Handle mouse event on irregular shaped objects with event delegation

I need to handle mouse events on a page where there are multiple irregular-shaped objects (for example, houses) are stacked on top of each other. If I use the normal way of event delegation jQuery .on(), the event source reported will always be the top most object, even if user clicked on the transparent part of the object (or image).
Example: <img> tag that contains the red triangle will always be the event source even if I click at the X position.
I can detect that mouse click is not inside the triangle. What I need is a way to "forward" the event to the green triangle below.
EDIT: My current approach is to catch the events on a big div that wraps everything, then use jQuery selector and compare coordinates to find out which object is under the mouse, then check if the mouse is in transparent part or not. It works fine, but seems to be slow and consume a lot of memory, especially with mouse move events being fired continuously.
EDIT 2:
This image was extracted from Building a game engine with jQuery, and my approach was almost identical to that. And now, this is the question:
Are you drawing complex graphics using plain HTML elements? Not sure about your exact needs, but it might make more sense to use SVG or Canvas, where catching click events on shapes becomes much easier.

javascript mouseover while dragging

I'm trying to implement a drag and drop script and have hit the wall with one problem. When you take an item and start dragging it - the item is directly below your cursor and onmouseover event is very rarely fired on the items below. But i want other items to highlight when i drag something over them. One of the solutions would be not to drag anything at all - that way the mouse events would work, but that would look ugly. Has anyone ever done something like this and know how to overcome this problem?
If you're thinking about suggesting some JQuery plugin or something like that - please don't. I don't need a completed solution, this is educational.
IMO, in order to have the mouseover event to be fired up frequently would be binding the mouseover event to the parent element of all the affected elements, or perhaps to the document itself, since events get bubbled up, they are probably the only elements that can fire the mouseover events.
Then further, write a hit method in your mouseover event and actively check the position of your mouse cursor, see whether it's going under the target element's boundary. Tradeoff in usability and performance. You choose.
My 2cents.
Or perhaps, you can reverse engineer jQuery UI to see how they implement the drag element. Haven't check thou, but I think there should be a wiser way.

Categories

Resources