Overview:
I have a page which uses jquery.event.drag and jquery.event.drop.
I need to be able to drag and drop onto elements which are constantly being added to the dom, even after the drag has started.
Problem:
When the dragstart event fires it checks for available drop targets and adds them to the drag object.
The problem I have is I am adding drop targets dynamically, after the dragstart event has fired, and therefore the user cannot drop onto these dynamically added drop targets.
Example:
http://jsfiddle.net/blowsie/36AJq/
Question:
How can I update the drag to allow dropping on elements which have been added to the dom after drag has started?
You can use this snippet.
The important function is: $.event.special.drop.locate();
Tested on chrome/safari/firefox/ie9 and seems to work.
SEE DEMO
UPDATE
For overlapping events, see if following code works. I set it inside an anonymous function just to avoid any global variable.
Idea is to use currentTarget property of event to check if not the same element is triggering same event. I set an id on newdrop element just in purpose of test here.
SEE UPDATED DEMO
(function () {
var $body = $("body"),
newdrops = [],
currentTarget = {},
ondragstart = function () {
$(this).css('opacity', .75);
}, ondrag = function (ev, dd) {
$(this).css({
top: dd.offsetY,
left: dd.offsetX
});
}, ondragend = function () {
$(this).css('opacity', '');
for (var i = 0, z = newdrops.length; i < z; i++)
$(newdrops[i]).off('dropstart drop dropend').removeClass('tempdrop');
newdrops = [];
}, ondropstart = function (e) {
if (currentTarget.dropstart === e.currentTarget) return;
currentTarget.dropstart = e.currentTarget;
currentTarget.dropend = null;
console.log('start::' + e.currentTarget.id)
$(this).addClass("active");
}, ondrop = function () {
$(this).toggleClass("dropped");
}, ondropend = function (e) {
if (currentTarget.dropend === e.currentTarget) return;
currentTarget.dropend = e.currentTarget;
currentTarget.dropstart = null;
console.log('end::' + e.currentTarget.id)
$(this).removeClass("active");
};
$body.on("dragstart", ".drag", ondragstart)
.on("drag", ".drag", ondrag)
.on("dragend", ".drag", ondragend)
.on("dropstart", ".drop", ondropstart)
.on("drop", ".drop", ondrop)
.on("dropend", ".drop", ondropend);
var cnt = 0;
setInterval(function () {
var dataDroppables = $body.data('dragdata')['interactions'] ? $body.data('dragdata')['interactions'][0]['droppable'] : [];
var $newDrop = $('<div class="drop tempdrop" id="' + cnt + '">Drop</div>');
cnt++;
$("#dropWrap").append($newDrop);
var offset = $newDrop.offset();
var dropdata = {
active: [],
anyactive: 0,
elem: $newDrop[0],
index: $('.drop').length,
location: {
bottom: offset.top + $newDrop.height(),
elem: $newDrop[0],
height: $newDrop.height(),
left: offset.left,
right: offset.left + $newDrop.width,
top: offset.top,
width: $newDrop.width
},
related: 0,
winner: 0
};
$newDrop.data('dropdata', dropdata);
dataDroppables.push($newDrop[0]);
$newDrop.on("dropstart", ondropstart)
.on("drop", ondrop)
.on("dropend", ondropend);
$.event.special.drop.locate($newDrop[0], dropdata.index);
newdrops.push($newDrop[0]);
}, 1000);
})();
I wasn't able to get this working using jquery.event.drag and jquery.event.drop, but I did make it work with the native HTML5 events:
http://jsfiddle.net/R2B8V/1/
The solution was to bind the events on the drop targets within a function and call that to update the bindings. I suspect you could get this working with jquery.event.drag and jquery.event.drop using a similar principal. If I can get those working I will update my answer.
Here is the JS:
$(function() {
var bind_targets = function() {
$(".drop").on({
dragenter: function() {
$(this).addClass("active");
return true;
},
dragleave: function() {
$(this).removeClass("active");
},
drop: function() {
$(this).toggleClass("dropped");
}
});
};
$("div[draggable]").on({
dragstart: function(evt) {
evt.originalEvent.dataTransfer.setData('Text', 'data');
},
dragend: function(evt) {
$('.active.drop').removeClass('active');
}
});
setInterval(function () {
$("#dropWrap").append('<div class="drop">Drop</div>');
// Do something here to update the dd.available
bind_targets();
}, 1000)
});
You can't. On dragstart, possible drop zones are calculated from the DOM, and can't be edited until dragend. Even constantly rebinding the .on() (Demo: http://jsfiddle.net/36AJq/84/) will not provide the desired effect.
I solved the issue a little differently. (Demo: http://jsfiddle.net/36AJq/87/)
Start with every <div> in the HTML.
Apply opacity: 0 to make it invisible, and width: 0 to keep it from getting a dropend when hidden.
Use setInterval to show the next hidden div ($('.drop:not(.visible)').first()) each 1000ms.
JS:
$("body")
.on("dragstart", ".drag", function () {
$(this).css('opacity', .75);
})
.on("drag", ".drag", function (ev, dd) {
$(this).css({
top: dd.offsetY,
left: dd.offsetX
});
})
.on("dragend", ".drag", function () {
$(this).css('opacity', '');
})
.on("dropstart", ".drop", function () {
$(this).addClass("active");
})
.on("drop", ".drop", function () {
$(this).toggleClass("dropped");
})
.on("dropend", ".drop", function () {
$(this).removeClass("active");
});
setInterval(function () {
$('.drop:not(.visible)').first()
.addClass('visible').removeClass('hidden');
}, 1000)
Enable the refreshPositions option.
Why not place all the divs into the page and set their visibility to hidden? Then use setInterval() to change each one's visibility every second.
Related
Is there a way how to add listener "droppable" to element, which is actually hovered while dragging "draggable" element?
I've tried this, but it does not work.
$("#draggable span.item").draggable({
helper: "clone",
drag: function(event, ui) {
var pos = ui.position;
var element = document.elementFromPoint(pos.left, pos.top);
$(element).droppable({
classes: {
"ui-droppable-hover": "hover"
},
drop: function(event, ui) {
console.log('dropped');
}
});
}
});
I am trying this because I need apply "droppable" to many elements and classic way via jQuery $("#droppable span.item").droppable(); is very slow in this case. So I would like to init "droppable" listener only for elements, which are hovered while dropping.
did you try this
$(document).ready(function() {
var $dragging = null;
$(document.body).on("mousemove", function(e) {
if ($dragging) {
$dragging.offset({
top: e.pageY,
left: e.pageX
});
}
});
$(document.body).on("mousedown", "div", function (e) {
$dragging = $(e.target);
});
$(document.body).on("mouseup", function (e) {
$dragging = null;
});
});
I have some line of codes which will move an element to mouse position after it is mousedown-ed.
I want to remove the event attached to it, so it won't following the mouse position anymore after it is mouseup-ed!
The Problem
The element still follows the mouse after mouseup!
I want it to follow the mouse on mousedown and stop following the mouse after mouseup! How do I remove the mousemove listener from the element?
Here is the JS
jQuery(document).ready(function ($) {
$(".crossY").on("mousedown", function (e) {
var j = $(this);
$(document).on("mousemove", function (e) {
j.css({
"top": e.pageY,
"left": e.pageX
});
});
})
$(".crossY").on("mouseup", function (e) {
var j = $(this);
$(document).on("mousemove", function (e) {
j.css({
"top": j.css("top"),
"left": j.css("left")
});
});
});
});
and the FIDDLE DEMO
In order to remove a mouse listener, you need to use the jQuery .off method. In order to get this to work easily, you should namespace the mousemove event. This will allow you to easily detach the necessary mousemove listener.
Inside the mousedown we want to attach the listener
$(document).on('mousemove.following', function (e) { /* my event handler */ })
Inside the mouseup we want to detach the listener
$(document).off('mousemove.following')
The following namespace makes sure that no other event listeners are detached.
Here is an example of this working (your jsfiddle except updated).
Another thing you might want to do is make the moving part centered underneath the mouse.
$(".crossY").on("mousedown", function (e) {
var j = $(this);
var height = j.height(), width = j.width();
$(document).on("mousemove", function (e) {
j.css({
"top": e.pageY - height/2,
"left": e.pageX - width/2,
});
});
})
Subtracting half of the element height and width keeps the element centered underneath the mouse, which will also ensure that the mouseup even is fired.
try using bind() and unbind() like this: DEMO
jQuery(document).ready(function ($) {
$(".crossY").on("mousedown", function (e) {
var j = $(this);
$(document).bind("mousemove", function (e) {
j.css({
"top": e.pageY-10,
"left": e.pageX-10
});
});
})
$(".crossY").on("mouseup", function (e) {
var j = $(this);
$(document).unbind("mousemove");
});
});
Try
jQuery(document).ready(function ($) {
$(".crossY").on("mousedown", function (e) {
var j = $(this);
$(document).on("mousemove", function (e) {
j.css({
"top": e.pageY,
"left": e.pageX
});
});
})
$(".crossY").on("mouseup", function (e) {
var j = $(this);
$(document).off("mousemove");
});
});
I have an element which I want to expand on click and then collapse on click outside and thus came up with the following code. However when I run this it will start to expand and then immediately collapse since both functions are called sequentially. I don't understand why and how to solve this.
jQuery(document).ready(function() {
var element = jQuery("#search-main");
var defaultWidth = jQuery("#search-main").css('width');
var expandWidth = "200px";
var fnSearch = {
expand : function() {
jQuery(element).animate({
width : expandWidth
});
jQuery(document).bind('click', fnSearch.collapse);
},
collapse : function() {
jQuery(element).animate({
width : defaultWidth
});
event.stopPropagation();
jQuery(document).unbind("click", fnSearch.collapse);
}
}
jQuery("#search-main").bind("click", fnSearch.expand);
});
You are having the problem because the #search-main click event is propagating to the document; i.e. first the #search-main click event triggers, then the document click event triggers. Click events do this by default. To stop this event propagation, you want to use http://api.jquery.com/event.stoppropagation/ in your expand function:
jQuery(document).ready(function() {
var element = jQuery("#search-main");
var defaultWidth = jQuery("#search-main").css('width');
var expandWidth = "200px";
var fnSearch = {
expand : function(event) { // add event parameter to function
// add this call:
event.stopPropagation();
jQuery(element).animate({
width : expandWidth
});
jQuery(document).bind('click', fnSearch.collapse);
},
collapse : function() {
jQuery(element).animate({
width : defaultWidth
});
jQuery(document).unbind("click", fnSearch.collapse);
}
}
jQuery("#search-main").bind("click", fnSearch.expand);
});
That said, Jason P's solution is better for what you want. It's more reliable and less messy, since you don't have to bind stuff to the document, which can easily become hard to track and cause conflicts with other code if you use that strategy habitually.
You could unbind the click event from the #search-main element after clicking, or stop the propagation of the event, but I would recommend binding to the blur and focus events instead:
http://jsfiddle.net/6Mxt9/
(function ($) {
$(document).ready(function () {
var element = jQuery("#search-main");
var defaultWidth = jQuery("#search-main").css('width');
var expandWidth = "200px";
$('#search-main').on('focus', function () {
$(element).animate({
width: expandWidth
});
}).on('blur', function () {
$(element).animate({
width: defaultWidth
});
});
});
})(jQuery);
That way, it will work even if the user tabs in or out of the field.
I have tried to built a continuous content slider in jQuery.
If you don't hover over it, then it works fine, it slides (even though I feel like I made it happen in a wrong way).
When you hover it then it stops, but only for 2 seconds. As you'd imagine, it should stay stopped until the cursor is removed. Maybe the interval is not cleared properly?
Generally the whole thing works improperly when you starts to hover/unhover.
Here's a demo of my plugin: http://jsfiddle.net/T5Gt3/
(function ($) {
$.fn.productSlider = function(options) {
var defaults = {
speed: 2000
};
var config = $.extend(defaults, options);
this.each(function() {
var $this = $(this),
$scrollable = $this.find('#content-product-slider-inner'),
timeLeft;
function animateScrollable() {
$scrollable.animate({ left: '-120px' }, config.speed, 'linear', function() {
$scrollable.css({ left: '0px' }).find('a:first-child').remove().appendTo($scrollable);
});
};
animateScrollable();
var timer = setInterval(animateScrollable, config.speed);
$scrollable.mouseover(function() {
$scrollable.stop();
clearInterval(timer);
});
$scrollable.mouseout(function() {
animateScrollable();
var timer = setInterval(animateScrollable, config.speed);
});
});
return this;
};
})(jQuery);
Any help would be greatly appreciated.
$(".event_list_inner_wrapper").live({
mouseenter: function () {
$(this).find('.front_side').fadeOut(600).hide();
$(this).find('.back_side').fadeIn(600).show();
},
mouseleave: function () {
$(this).find('.back_side').fadeOut(600).hide();
$(this).find('.front_side').fadeIn(600).show();
}
});
That's code I used for a project that was similar to your description. Basically, bind the mice events, and do your thing.
It possible to check if the cursor is hovering on an element.
Something like
$("#divId").is("hover");
NOTE: I just want to check not set event.
.is(':hover');
or
$('#divId:hover');
Updated answer!
$("#foo").hover(function() {
$(this).data("hovered", true);
}, function() {
$(this).data("hovered", false);
});
Testing if it is hovered...
if ( $("#foo").data("hovered") ) {
// it is hovered
} else {
// it's not hovered
}
You can use jQuery's hover(), mouseenter() or mouseover()
$("#divId").hover(function() { alert("hovering"; });
This will fire on mouseenter and mouseleave. You can add separate event handlers for each.
So if you want to do something like, if hovering over #divId increase x by one, and when you stop hovering decrease y by one:
$("#divId").hover(function() { ++x; },
function() { --y; });
If you really want an if hovering:
var hovering = 0;
$("#divId").hover(function() { hovering = 1; },
function() { hovering = 0; });
...
// Then inside somewhere useful. Maybe in a setInterval, or triggered by
// another action...
if (hovering) { ...
Try it out with this jsFiddle
For example:
$(function() {
var hovering = 0;
$("div").hover(function() { hovering = 1; },
function() { hovering = 0; });
$(document).keyup(function() {
if (hovering) alert("hovering!"); // This is the "if hovering"
else alert("not hovering.");
});
});
You can use .hover(). It's can be used like so:
$("selector").hover(
function (){
//mouse over
},
function (){
//mouse out
}
);
An example of it's use from the documentation is here:
$("li").hover(
function () {
$(this).append($("<span> ***</span>"));
},
function () {
$(this).find("span:last").remove();
}
);
Depending on what you are doing either mouseover() (http://api.jquery.com/mouseover/) or hover() (http://api.jquery.com/hover/) can be useful.