Unable to drop an element on mouseup event - javascript

Here is the jQuery code that I have written to drag multiple items at a time. It is draggable now but not droppable.
here is the code
$(document).on('click', function (e) {
var target = e.target;
if (!$(target).hasClass('a')) $('.selected').removeClass('selected');
});
$(document).delegate('.a', 'dblclick', function (e) {
$(this).addClass('selected');
});
$(document).delegate('.selected', 'mousedown', function (e) {
var div = $('<div></div>');
$('.selected').each(function () {
div.append($(this).clone());
});
div.prop('id', 'currentDrag');
$('#currentDrag').css({
left: e.pageX + "px",
top: e.pageY + "px"
});
$('body').append(div);
});
$(document).on('mouseup', function (e) {
var tgt = e.target;
var mPos = {
x: e.pageX,
y: e.pageY
};
$('.drop').each(function () {
var pos = $(this).offset(),
twt = $(this).width(),
tht = $(this).height();
});
if((mPos.x > pos.left) && (mPos.x < (pos.left + twt)) && (mPos.y > targPos.top) && (mPos.y < (pos.top + tht))) {
$(this).append($('#currentDrag').html());
}
$('.drop .selected').removeClass('selected');
$('#currentDrag').remove();
});
$('.drop').on('mouseup', function (e) {
$(tgt).append($('#currentDrag').html());
$('.drop .selected').removeClass('selected');
$('#currentDrag').remove();
});
$(document).on('mousemove', function (e) {
$('#currentDrag').css({
left: e.pageX + "px",
top: e.pageY + "px"
});
});
What is the pronblem with my code and how can I achieve this. here is the fiddle http://jsfiddle.net/mDewr/27/

I would really recommend trying to find a way to make the jQuery UI draggable and droppable libraries work for you. Then the question becomes,
similar to this one: How do I drag multiple elements with JavaScript or jQuery?.
Here's how we can apply one of the answers from that question to your problem. I'm using the jQuery UI multiple draggable plugin, the entire script of which can be found here: jquery.ui.multidraggable-1.8.8.js.
First let's simplify your HTML. By putting our draggable and dropable divs inside of elements, we don't have to apply redundant stylings to each one. Instead we can use the containing element to style
HTML
<div id="parent">
<div id="dragTargets">
<div>123</div>
<div>456</div>
<div>789</div>
</div>
<div id='dropTargets'>
<div></div>
<div></div>
</div>
</div>
Using the plugin we can call multidraggable on each of the drag divs. And droppable anywhere they can be dropped
JavaScript
$("#dragTargets div").multidraggable();
$("#dropTargets div").droppable();
Customize
We can control the appearance with styling. As an example, we'll make anything that can receive drops yellow, anything you're about to drop as red, and anything that has received an element green.
Here's some styling as an example in CSS
.ui-state-highlight { background: green; }
.ui-state-active { background: yellow; }
.ui-state-hover { background: red; }
And we'll control when these classes are applied with JavaScript:
$("#dropTargets div").droppable({
activeClass: "ui-state-active",
hoverClass: "ui-state-hover",
drop: function () {
$(this).addClass("ui-state-highlight")
}
});
Multi-Draggable
You should style the elements that are currently selected. The script will apply the class ui-multidraggable to all the currently selected elements. The following CSS will make it apparent to the user that their choice is selected.
.ui-multidraggable {
background: tan;
}
Check out this demo. Just hold down ctrl to select more than one of the divs and then drag all of them at once.
jsFiddle

There are few errors in you code. You can check errors on browser console.
To check elements over droppable area, you should check the drop area in the each loop, rather than after each loop. When moving mouse, you should better turn off selection to avoid selected text flashing
$(document).on('click', '.a', function (e) {
$(this).removeClass('selected');
});
$(document).on('dblclick', '.a', function (e) {
$(this).toggleClass('selected');
});
$(document).on('mousedown', '.selected', function (e) {
var dragMode = true;
var div = $('<div></div>');
$('.selected').each(function () {
div.append($(this).clone());
});
div.prop('id', 'currentDrag');
$('#currentDrag').css({
left: e.pageX + "px",
top: e.pageY + "px"
});
$('body').append(div);
//disable selection on dropping start
disableSelection();
$(document).on('mousemove.drop', function(e){
onDragging(e, dragMode);
});
$(document).on('mouseup.drop', function(e){
onDragEnd(e, dragMode);
});
});
function onDragEnd(e, dragMode){
if(!dragMode)
return;
var tgt = e.target;
var mPos = {
x: e.pageX,
y: e.pageY
};
$('.drop').each(function () {
var pos = $(this).position(),
twt = $(this).width(),
tht = $(this).height();
if((mPos.x > pos.left) &&
(mPos.x < (pos.left + twt)) &&
(mPos.y > pos.top) &&
(mPos.y < (pos.top + tht))) {
$(this).append($('#currentDrag').html());
}
});
$('.drop .selected').removeClass('selected');
$('#currentDrag').remove();
$('.onDrop').removeClass('onDrop');
//remove listener on docuemnt when drop end
$(document).off('mousemove.drop');
$(document).off('mouseup.drop');
//enable selection
enableSelection();
}
function onDragging(e, dragMode){
if(!dragMode)
return;
var p = $('body').offset();
var mPos = {
x: e.pageX,
y: e.pageY
};
$('#currentDrag').css({
left: mPos.x,
top: mPos.y
});
$('.drop').each(function () {
var pos = $(this).position(),
twt = $(this).width(),
tht = $(this).height();
$(this).toggleClass("onDrop",
(mPos.x > pos.left)
&& (mPos.x < (pos.left + twt))
&& (mPos.y > pos.top)
&& (mPos.y < (pos.top + tht))
);
});
}
function disableSelection(){
$(document).on("selectstart", function(){ return false; });
//firefox
$("body").css("-moz-user-select", "none");
}
function enableSelection(){
$(document).off("selectstart");
//firefox
$("body").css("-moz-user-select", "");
}
I updated your code: http://jsfiddle.net/mDewr/46/, may can help you.

There were several errors, which I'll not list now, but you can compare the old version with the new one.
$(document).on('dblclick', '.a', function (e) {
$(this).toggleClass('selected');
});
$(document).on('mousedown', '.selected', function (e) {
var div = $('<div id="currentDrag"></div>');
$('.selected').each(function () {
div.append($(this).clone(true));
});
var p = $('body').offset();
var l = e.pageX - p.left;
var t = e.pageY - p.top;
console.log(l, ', ', t);
$('body').append(div);
$('#currentDrag').css({
left: l,
top: t
});
});
$(document).on('mouseup', '.selected', function (e) {
$('.d').each(function(index, item){
var $i = $(item);
if (e.pageX >= $i.offset().left &&
e.pageX <= $i.offset().left + $i.width() &&
e.pageY >= $i.offset().top &&
e.pageY <= $i.offset().top + $i.height()) {
console.log('Dropped');
var $cl = $('#currentDrag').find('>*').clone(true);
$i.append($cl);
}
});
$('.selected').removeClass('selected');
$('#currentDrag').remove();
});
$(document).on('mousemove', function (e) {
var p = $('body').offset();
$('#currentDrag').css({
left: e.pageX - p.left,
top: e.pageY - p.top
});
});
http://jsfiddle.net/mDewr/43/
Everything should work perfectly in this version (this is an update).
PS: I've changed to 1.7+ jQuery, but you can easily change it back to <1.7. Also you don't need custom attributes, use css classes instead.

Related

Need to set the minimum width for Click & drag column headers

I need to set the maximum width for the table header while click and drag.
I had tried the max-width and width in the css.
th {
position: relative;
max-width: 5px;
}
But no use on that. Here is the link for my code:
https://codepen.io/jasongardner/pen/QNOXym
I need to fix the width for drag the table for certain distance.
I have fixed your problem. Change your Javascript to this:
$(function() {
var startX,
startWidth,
$handle,
$table,
pressed = false;
$(document).on({
mousemove: function(event) {
if (pressed) {
var newWidth = startWidth + (event.pageX - startX);
if (newWidth > 300) {
$handle.width(300);
} else {
$handle.width(startWidth + (event.pageX - startX));
}
}
},
mouseup: function() {
if (pressed) {
$table.removeClass('resizing');
pressed = false;
}
}
}).on('mousedown', '.table-resizable th', function(event) {
$handle = $(this);
pressed = true;
startX = event.pageX;
startWidth = $handle.width();
$table = $handle.closest('.table-resizable').addClass('resizing');
}).on('dblclick', '.table-resizable thead', function() {
// Reset column sizes on double click
$(this).find('th[style]').css('width', '');
});
});
This is the code I changed:
if (pressed) {
var newWidth = startWidth + (event.pageX - startX);
if (newWidth > 300) {
$handle.width(300);
} else {
$handle.width(startWidth + (event.pageX - startX));
}
}
I created the variable "newWidth" and check if it's bigger than 300. Only when it's smaller, it sets the new width. So actually you can just replace the 300 with any number you want to define as the max-width.
Hope this helps

Jquery stop event for context menu

I'm making a context menu, but there a problem for my context menu, when I right click I wish the context menu stop on the position. I have tried using .stop() but it doesn't work.
This is the JS Fiddle
JQUERY
$(".menu").hide();
$(document).on("contextmenu", ".element", function (e) {
$(".menu").fadeIn();
return false;
});
$(document).mouseup(function (e) {
$(".menu").fadeOut(300);
});
$(document).bind('mousemove', function(e){
$('.menu').css({
left: e.pageX + 20,
top: e.pageY
});
$(".menu").stop();
});
Here's one approach where you check if the menu is visible and don't move it if it is.
var $menu = $(".menu").hide();
$(document).on("contextmenu", ".element", function (e) {
$menu.fadeIn();
return false;
});
$(document).mouseup(function (e) {
$menu.fadeOut(300);
});
$(document).bind('mousemove', function (e) {
if ($menu.is(':visible')) {
return;
}
$menu.css({
left: e.pageX + 20,
top: e.pageY
});
});
DEMO
Alternatively you can use the contextmenu event to set menu position without using mousemove.
$(document).on("contextmenu", ".element", function (e) {
$menu.css({
left: e.pageX + 20,
top: e.pageY
}).fadeIn();
return false;
});
DEMO 2

Custom right click menu only show on children of div

http://jsfiddle.net/TnbYm/
I'm trying to get my right click menu to only show on children of #canvas. I also want to have it remove when a child is not clicked, but one of the problems are because document is being called as the container document closes it before the action is called.
If anyone can help me with this it'll be greatly appreciated.
if ( $("#tm").prop('checked') === true ) {
// Trigger action when the contexmenu is about to be shown
$("#canvas").find("*").bind("contextmenu", function (event) {
// Avoid the real one
event.preventDefault();
$("#custom-menu").hide(100);
// Show contextmenu
if ($("#showcustom-menu").show() === true) {
$("#custom-menu").hide(100).
// In the right position (the mouse)
css({
top: event.pageY + "px",
left: event.pageX + "px"
});
} else {
$("#custom-menu").show(100).
// In the right position (the mouse)
css({
top: event.pageY + "px",
left: event.pageX + "px"
});
}
});
// If the document is clicked somewhere
$(document).bind("mousedown", function () {
$("#custom-menu").hide(100);
});
} else {
$(document).unbind("contextmenu");
}
$("#tm").on('change', function() {
if ( $(this).prop('checked') === true ) {
// Trigger action when the contexmenu is about to be shown
$("#canvas").find("*").bind("contextmenu", function (event) {
// Avoid the real one
event.preventDefault();
$("#custom-menu").hide(100);
// Show contextmenu
if ($("#custom-menu").show() === true) {
$("#custom-menu").hide(100).
// In the right position (the mouse)
css({
top: event.pageY + "px",
left: event.pageX + "px"
});
} else {
$("#custom-menu").show(100).
// In the right position (the mouse)
css({
top: event.pageY + "px",
left: event.pageX + "px"
});
}
});
// If the document is clicked somewhere
$(document).bind("mousedown", function () {
$("#custom-menu").hide(100);
});
} else {
$(document).unbind("contextmenu");
}
});
// Menu's button actions
$("#custom-menu > button").click(function() {
alert($(this).text() + "was clicked");
});
$("#custom-menu > button#duplicate").click(function() {
// $('#canvas').append($(this).clone());
$("#custom-menu").hide(100);
});
$("#custom-menu > button#remove").click(function() {
// $(this).remove();
$("#custom-menu").hide(100);
});
$("#custom-menu").find("button#deselect, button#close").click(function() {
$("#custom-menu").hide(100);
});
You can use CSS selectors for that:
$(document).on('contextmenu', function (e) {
if (e.target.matches('#canvas *'))
alert('Contexted!');
else
alert('Not contexted!');
});
Element.matches
Fiddle
Hi i have updated the jsfiddle provided by you please go through that..
its working fine and you can add code into the click method according to your need.
Link for jsfiddle:- http://jsfiddle.net/TnbYm/14/

Toggling a absolute DIV is not working after firsttime

$('.pallete').hide();
$(document).delegate('.pick', 'click', function () {
var pos = $(this).offset();
var x = pos.left - $(window).scrollLeft() + $(this).width();
var y = pos.top - $(window).scrollTop() + $(this).height();
$('.pallete').css({
top: y + "px",
left: x + "px",
}).show();
});
$(document).delegate('.col', 'click', function () {
var pos = $(this).css('background-color');
$('.pick').css('background-color', pos);
$(this).parents('div').fadeOut();
});
Here is the fiddle, http://jsfiddle.net/zPNk3/5/.
The problem is when I click first time on .pick element the '.palette' element is shown properly. But when I click next time the same is not working.
When you do $(this).parents('div').fadeOut(), you’re fading out all <div> parents of the element. You’re only showing .pallete.
Try:
$(this).closest('.pallete').fadeOut();
It works!
Look at the row div, that should not be hidden,
$(document).delegate('.col', 'click', function () {
var pos = $(this).css('background-color');
$('.pick').css('background-color', pos);
//$(this).parents('div').fadeOut(); // this is wrong
$(this).parent().parent().fadeOut(); // fixed
});

How to remove selected image on a div when you click on it?

I am fairly new to Javascript and would like to create a div whereby it allows a person to define points on it by clicking on the area within the div. An image will be added to represent the point clicked. Thereafter, if the person wants to remove this point, upon clicking on the image, it should be remove.
I have done the part whereby it allows a person to define the points based on a minor modification to an existing fiddle: http://jsfiddle.net/uKkRh/1/
Reference: jquery how to add pin to image and save the position to SQL
I also manage to remove all the images by click on the button.
However, I am still short of how to remove the image from the div when the person clicks on the image.
I have tried the following:
$('#container >img').click(function() {
var selectedImg = $(this);
selectedImg.remove();
return;
});
but it works itermitently.
Please see my JSfiddle for my sample. http://jsfiddle.net/WindSaviour/rUNsJ/19/
var point = [];
var id = 0;
$(document).ready(function() {
var output = $('#container');
$("#container").click(function(e) {
e.preventDefault();
var isPointPresent = false;
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
console.log("Mouse Click Pos (x=" + x + ", y=" + y + ")");
for(var i=0; i< point.length; i++) {
if(x >= point[i].min_x && x<=point[i].max_x) {
if(y >= point[i].min_y && y<=point[i].max_y) {
isPointPresent = true;
point.splice(i,1);
break;
}
}
}
point[point.length] = { "x-pos": x, "y-pos":y, "min_x": x-25, "max_x": x+25, "min_y": y-83, "max_y": y};
if(isPointPresent) {
$('#container >img').click(function() {
var selectedImg = $(this);
selectedImg.remove();
return;
});
}
var img = $('<img>');
var left = x-25;
var top = y-83;
console.log("Img Start Pos (x=" + left + ", y=" + top + ")");
img.css('top', top);
img.css('left', left);
img.attr('src', 'http://www.clker.com/cliparts/P/w/G/0/N/o/google-map-th.png');
img.attr('id', id);
img.appendTo('#container');
/*
*/
id++;
})
});
$('#remove').click(function() {
$('#container > img').remove();
});
Try this http://jsfiddle.net/uKkRh/635/, but you need a newer verion of jQuery
$('#container').on('click', 'img', function (e) {
e.stopPropagation();
$(this).remove();
});

Categories