Create an image every time I click a button JS - javascript

I want to create one image each time I click on a button and I will need to be able to drag this each image to move it where I want.
At this moment my code works only for one image.
I think I need to create my div in JS but this doesn't work..
const CreerPerso = document.getElementById('createPerso');
CreerPerso.onclick = CreationPersonnage;
async function CreationPersonnage() {
/*var divImg = document.createElement('div');
divImg.setAttribute("id", "imgPerso");
document.getElementById('body').appendChild(divImg);*/
document.getElementById("imgPerso").innerHTML = "<img src='images/circle.png' />";
//drag images Personnage
dragElement(document.getElementById("imgPerso"));
function dragElement(elmnt) {
var pos1 = 0,
pos2 = 0,
pos3 = 0,
pos4 = 0;
if (document.getElementById(elmnt.id)) {
// if present, the header is where you move the DIV from:
document.getElementById(elmnt.id).onmousedown = dragMouseDown;
} else {
// otherwise, move the DIV from anywhere inside the DIV:
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
}
}
}
<body id="body">
<button id="createPerso" class="btn btn-primary">Créer Personnage</button>
<div id="imgPerso">
</div>
</body>

Id's in HTML need to be unique, so you should add a counter or something to the div you create and keep that id for future reference.
var personImageIdCount = 0;
async function CreationPersonnage() {
var personImageId = "imgPerso_" + (personImageIdCount++).toString();
var divImg = document.createElement('div');
divImg.setAttribute("id", personImageId);
document.getElementById('body').appendChild(divImg);

No need for async
No need to give body an ID
You pass the element, no need to get the ID to get the element
IDs need to be unique
This is simpler
function dragElement(elmnt) {
elmnt.dataset.pos1 = 0,
elmnt.dataset.pos2 = 0,
elmnt.dataset.pos3 = 0,
elmnt.dataset.pos4 = 0;
// if present, the header is where you move the DIV from:
elmnt.addEventListener("mousedown", dragMouseDown);
}
function dragMouseDown(e) {
e.preventDefault();
const elemt = e.target;
// get the mouse cursor position at startup:
elemt.dataset.pos3 = e.clientX;
elemt.dataset.pos4 = e.clientY;
}
function elementDrag(e) {
e.preventDefault();
const elemt = e.target;
if (elemt) {
// calculate the new cursor position:
let pos1 = elemt.dataset.pos3 - elemt.clientX;
let pos2 = elemt.dataset.pos4 - elemt.clientY;
let = elemt.clientX;
let = elemt.clientY;
// set the element's new position:
elemt.style.top = (elemt.offsetTop - pos2) + "px";
elemt.style.left = (elemt.offsetLeft - pos1) + "px";
}
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
}
const CreerPerso = document.getElementById('createPerso');
const body = document.querySelector('body');
CreerPerso.addEventListener("click", CreationPersonnage);
function CreationPersonnage() {
const divImg = document.createElement('div');
divImg.classList.add("imgPerso");
divImg.innerHTML = "<img src='images/circle.png' />";
body.appendChild(divImg);
//drag images Personnage
dragElement(divImg);
}
document.addEventListener("mouseup", closeDragElement);
document.addEventListener("mousemove", elementDrag);
.imgPerso {
position: absolute
}
<button id="createPerso" class="btn btn-primary">Créer Personnage</button>

Related

Add click event after mouse up

I have a draggable element. After dragging, I want to add the click-funtion again.
The click-event should not fire when dragging, but I want to add it when dragging is over.
If I add my click-event again after dragging (line 46) it get's fired immediately
clickElemtent(document.getElementById("mydiv"));
I don't understand the logic.. Thank you so much!
dragElement(document.getElementById("mydiv"));
clickElemtent(document.getElementById("mydiv"));
function clickElemtent(elmnt) {
elmnt.onclick = function() {
alert("click")
}
}
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
elmnt.onclick = null;
e = e || window.event;
e.preventDefault();
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement(e) {
document.onmouseup = null;
document.onmousemove = null;
e.stopImmediatePropagation();
e.stopPropagation();
clickElemtent(document.getElementById("mydiv")); ///// ?????
}
}
#mydiv {
position: absolute;
z-index: 9;
background-color: #f1f1f1;
text-align: center;
border: 1px solid #d3d3d3;
}
#mydivheader {
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;
}
<div id="mydiv">
<div id="mydivheader">click OR drag</div>
</div>
function closeDragElement(e) {
document.onmouseup = null;
document.onmousemove = null;
e.stopImmediatePropagation();
e.stopPropagation();
///// ?????
setTimeout(()=>
document.getElementById("mydiv").onclick = ()=>alert("click")
,100 //or set more milis
);
return true;
}
https://jsfiddle.net/t09758fb/1/
EDIT:
Becouse events like dragend click are combined of keydown, keyup - this is a key problem in Your example.
Hence JavaScript is not multithreaded - You never know which action will be fired from a handler,
but setTimeout makes Your task will probably run after other actions in surrounding code block.
mouseup and click are different events (even though both are caused by the same interaction!), so stopping one doesn't affect the other.
Event order
(An explanation to Bujaq's answer:)
An event's propagation path is determined before propagation. That means adding/removing click listeners in another click listener won't have any effect on the current event's path.
However, different event types can affect each other, even those from the same event source, e.g. a mouse click. Events are run in a fixed order; for mouse events, mouseup runs before click.
Taking the event loop into consideration: Calls to the event handlers are queued, so tasks added via setTimeout() will be run later. That is also the reason why 0 ms is enough, too.
That means, adding the onclick like that will only have an effect after the pending events have been handled.
Conditional call
You want to only accept click events if no dragging occured. That means we need a way to tell if dragging occured.
Dragging has always occured if a mousemove event happened after a mousedown event.
Since a click event is fired even when dragging, we can call the "actual" listener only when no dragging occured:
var clickHandler = function(e) {
alert("click");
};
dragElement(document.getElementById("mydiv"), clickHandler);
function dragElement(elmnt, clickCallback /*New*/) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
var isDragged = false; // New
if (document.getElementById(elmnt.id + "header")) {
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
elmnt.onmousedown = dragMouseDown;
}
if (clickCallback) {
elmnt.onclick = function(e) {
// Only call if no dragging occured
if (!isDragged) clickCallback(e);
};
}
function dragMouseDown(e) {
isDragged = false; // No dragging since now
e = e || window.event;
e.preventDefault();
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
isDragged = true; // Dragging occured
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement(e) {
document.onmouseup = null;
document.onmousemove = null;
}
}
#mydiv {
position: absolute;
z-index: 9;
background-color: #f1f1f1;
text-align: center;
border: 1px solid #d3d3d3;
}
#mydivheader {
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;
}
<div id="mydiv">
<div id="mydivheader">click OR drag</div>
</div>
Capture and stop
Alternatively to conditionally calling the click listener, we can just stop the event from propagating.
We need to stop the event before it reaches the expected listener. This can be done in two ways:
With capturing listeners.
With earlier attached listeners.
Both ways require the use of addEventListener() to attach the listeners, which is the preferred way. The onevent properties and especially inline event attributes are generally discouraged.
In the end we want to make use of the event flow. Example:
const select = document.querySelector("select");
const button = document.querySelector("button");
// Notice order of attachment
button.addEventListener("click", function stopEarly(evt) {
if (select.value === "early") evt.stopImmediatePropagation();
});
button.addEventListener("click", () => console.log("Button reached!"));
button.addEventListener("click", function stopInCapture(evt) {
if (select.value === "capture") evt.stopPropagation();
}, { capture: true });
button.addEventListener("click", function stopEarly(evt) {
if (select.value === "late") evt.stopImmediatePropagation();
}, { capture: false /*default*/ });
<select>
<option value=none>No stopping</option>
<option value=capture>Stop in capture</option>
<option value=early>Stop early</option>
<option value=late>Stop late</option>
</select>
<button>Log text</button>
If we ensure that the propagation-stopping listener is called before the "intended" listener, we don't have to remove and reattach any listeners at all:
var clickHandler = function(e) {
alert("click");
};
dragElement(document.getElementById("mydiv"), clickHandler);
function dragElement(elmnt, clickCallback /*New*/) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
var isDragged = false; // New
if (document.getElementById(elmnt.id + "header")) {
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
elmnt.onmousedown = dragMouseDown;
}
if (clickCallback) {
elmnt.addEventListener("click", function(e) {
// Stop here if dragging occured
if (isDragged) e.stopImmediatePropagation();
}, { capture: true });
elmnt.addEventListener("click", clickCallback);
}
function dragMouseDown(e) {
isDragged = false; // No dragging since now
e = e || window.event;
e.preventDefault();
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
isDragged = true; // Dragging occured
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement(e) {
document.onmouseup = null;
document.onmousemove = null;
}
}
#mydiv {
position: absolute;
z-index: 9;
background-color: #f1f1f1;
text-align: center;
border: 1px solid #d3d3d3;
}
#mydivheader {
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;
}
<div id="mydiv">
<div id="mydivheader">click OR drag</div>
</div>
Apart from the three sections above, I want to demonstrate one more thing:
Event delegation
As seen in the event flow, an event goes through multiple phases:
The capture phase.
The target phase.
The bubbling phase.
Events propagate down to and up from their target. That means we can use a single listener on an ancestor for multiple targets. This is called event delegation.
Assuming that only one element can be dragged at once, we can attach a single listener on an ancestor, where we'll stop propagation when applicable.
Under these conditions, we can make elements automatically behave as wished simply by adding a class:
const button = document.querySelector("button");
// Add *click* listener to "click or drag" button
button.addEventListener("click", () => {
console.log("Initial button");
});
// Adding new draggable buttons is simple:
const button2 = document.createElement("button");
button2.classList.add("draggable"); // For dragging functionality
button2.classList.add("blue-button"); // For styling
button2.addEventListener("click", () => console.log("Button 2!")); // The *click* listener
button2.textContent = "Click or Drag 2";
document.body.append(button2);
(function pageWideDraggable() {
let target = null;
let isDragged = false;
document.addEventListener("mousedown", evt => {
// Get draggable target and reset "dragging memory"
target = event.target.closest(".draggable");
isDragged = false;
});
document.addEventListener("mousemove", evt => {
// If draggable target exists, remember that dragging occured and update target's position
if (!target) return;
isDragged = true;
target.style.top = `${target.offsetTop + evt.movementY}px`;
target.style.left = `${target.offsetLeft + evt.movementX}px`;
});
document.addEventListener("click", evt => {
// Capture click and stop event when dragging occured
if (isDragged) evt.stopPropagation();
target = null;
}, { capture: true });
})();
.draggable {
position: absolute;
padding: 0;
cursor: pointer;
user-select: none;
}
.blue-button {
padding: 10px;
display: inline-block;
color: white;
background-color: #2196F3;
}
<button class="draggable blue-button">
click OR drag
</button>
Sidenote: Notice how the deeper elements don't need to be aware of the capturing. This allows for easy component-based development.

Javascript Drag, Drop and bump other elements away

I have built out basic drag and drop feature that allows us to drag randomly placed absolute positioned elements within a container. Ideally I would want to push other elements that possibly intersect the dragged elements boundaries away, but I am presently unable find a solution.
I have this for the Drag and Drop Solution:
var draggableElements = document.getElementsByClassName("team_member");
for(var i = 0; i < draggableElements.length; i++){
dragElement(draggableElements[i]);
}
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
} else {
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
pos3 = parseInt(e.clientX);
pos4 = parseInt(e.clientY);
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
return false;
}
function elementDrag(e) {
e = e || window.event;
pos1 = pos3 - parseInt(e.clientX);
pos2 = pos4 - parseInt(e.clientY);
pos3 = parseInt(e.clientX);
pos4 = parseInt(e.clientY);
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
elmnt.classList.add("drag");
}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;
elmnt.classList.remove("drag");
}
}
This is a cool task to implement, I played a bit and came up with something like this, but for some reason it's a big buggy, my idea was to use the API : document.elementFromPoint() to get the intersecting element during the drag. It seems to work but it's a bit clumsy and sometimes it fails.
Probably it would work better with an IntersectionObserver, that could also make sure to handle multiple boundary drag ( for example if you have 3+ objects, object one will push object 2 that will push object 3, object 3 has to react ).
const draggableElements = document.querySelectorAll(".team_member");
draggableElements.forEach((el, i) => makeDraggable(el, i))
function makeDraggable(elem, idx) {
elem.onmousedown = dragMouseDown;
elem.position = {
x: 0,
y: 0,
prevX: 0,
prevY: 0
}
elem.style.left = `calc(35% + ${(idx* 60) + "px"})`
}
// ----- //
function dragMouseDown(e) {
e = e || window.event;
this.position.prevX = +(e.clientX);
this.position.prevY = +(e.clientY);
document.onmouseup = closeDragElement;
document.onmousemove = (e) => elementDrag(e, this);
return false;
}
function elementDrag(e, t) {
t.position.x = t.position.prevX - +(e.clientX);
t.position.y = t.position.prevY - +(e.clientY);
t.position.prevX = +(e.clientX);
t.position.prevY = +(e.clientY);
t.style.top = (t.offsetTop - t.position.y) + "px";
t.style.left = (t.offsetLeft - t.position.x) + "px";
t.classList.add("drag");
// Check intersection
const width = t.getBoundingClientRect().width
const height = t.getBoundingClientRect().height
const intersectionElemTop = document.elementFromPoint(e.clientX, e.clientY - height / 2)
const intersectionElemRight = document.elementFromPoint(e.clientX + width / 2, e.clientY)
const intersectionElemBottom = document.elementFromPoint(e.clientX, e.clientY + height / 2)
const intersectionElemLeft = document.elementFromPoint(e.clientX - width / 2, e.clientY)
const intersections = [{
type: "top",
node: intersectionElemTop
}, {
type: "right",
node: intersectionElemRight
}, {
type: "bottom",
node: intersectionElemBottom
}, {
type: "left",
node: intersectionElemLeft
}].filter(i => [...draggableElements].some(d => i.node === d && d !== t))
if (intersections[0]) {
const i = intersections[0]
switch (i.type) {
case "top":
{
i.node.style.top = t.getBoundingClientRect().y - height + "px";
}
break;
case "right":
{
i.node.style.left = t.getBoundingClientRect().x + width + "px";
}
break;
case "bottom":
{
i.node.style.top = t.getBoundingClientRect().y + height + "px";
}
break;
case "left":
{
i.node.style.left = t.getBoundingClientRect().x - width + "px";
}
break;
}
i.node.classList.add("dragged");
clearTimeout(i.timeout)
i.timeout = setTimeout(() => i.node.classList.remove("dragged"), 500);
}
}
function closeDragElement(e) {
document.onmouseup = null;
document.onmousemove = null;
e.target.classList.remove("drag");
}
.team_member {
position: fixed;
width: 50px;
height: 50px;
border: 2px solid red;
display: flex;
justify-content: center;
align-items: center;
cursor: grab;
top: calc(50% - 25px);
}
.drag {
background: blue;
}
.dragged {
background: red;
}
<div class="team_member">
One
</div>
<div class="team_member">
Two
</div>

How to stop a useEffect function with a condition?

I'm creating my portfolio website, and the concept is to create a cube that people can interact with. It is possible to move the cube by clicking and dragging the mouse on the cube/screen. However, I'ld like to be able to "lock" the cube, by using a useState (true/false).
Literally, if the cube "isLocked", then we shouldnt be able to use the function within the useEffect hook. Here is a part of my Cube component so far:
export default function Cube(props) {
const [isLocked, setIsLocked] = useState(false);
useEffect(() => {
if (!isLocked) {
rotateCube(document.getElementById("cube"));
} else {
return;
}
}, [isLocked]);
// Rotate function :
function rotateCube(cube) {
var mouseX0 = 0,
mouseY0 = 0,
mouseX1 = 0,
mouseY1 = 0;
cube.onmousedown = dragMouseDown;
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
mouseX0 = e.clientX;
mouseY0 = e.clientY;
document.onmouseup = closeDragElement;
...
}
Can put check inside dragMouseDown function
export default function Cube(props) {
const [isLocked, setIsLocked] = useState(false);
// executed once on load
useEffect(() => {
rotateCube(document.getElementById("cube"));
}, []);
// Rotate function :
function rotateCube(cube) {
var mouseX0 = 0,
mouseY0 = 0,
mouseX1 = 0,
mouseY1 = 0;
cube.onmousedown = dragMouseDown;
function dragMouseDown(e) {
// here the check
if (isLocked) { return false }
e = e || window.event;
e.preventDefault();
mouseX0 = e.clientX;
mouseY0 = e.clientY;
document.onmouseup = closeDragElement;
...
...
...
}
I wonder why you don't use JSX for handling events e.g. <Cube onMouseDown={onMouseDown} /> ?
Thank you for your answers !
I could actually find out what was happening. As you guys told me, I had to implement the isLocked within the rotateCube function, and place this entire function in the useEffect. Also, I forgot the place isLocked in the dependency array.
Here is the code :
useEffect(() => {
rotateCube(document.getElementById("cube"));
// Rotate function :
function rotateCube(cube) {
var mouseX0 = 0,
mouseY0 = 0,
mouseX1 = 0,
mouseY1 = 0;
if (isLocked === true) {
cube.onmousedown = closeDragElement;
}
if (isLocked === false) {
cube.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
mouseX0 = e.clientX;
mouseY0 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// Get new cursor position :
mouseX1 = e.clientX - mouseX0;
mouseY1 = (e.clientY - mouseY0) * -1;
//Set the new cube position :
cube.style.transform =
"rotateX(" + mouseY1 / 2 + "deg) rotateY(" + mouseX1 / 2 + "deg)";
}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;
}
}
}, [isLocked]);

Make it so image doesn't move around when user tries to resize the image

As the title states I want the user to be able to resize an image without the user being able to drag the image around.
I have it so the user can drag the image around so they can overlay on top of each other, but I also want to add the functionality that the user can resize any of the images. I'm doing this through CSS/JS.
My sources for how to drag comes from here: https://www.w3schools.com/howto/howto_js_draggable.asp
My source for how to resize images comes from here: https://jqueryui.com/resizable/
Currently when a user tries to resize the img, the img also gets dragged around.
Example of my problem here: https://jsfiddle.net/3ybsd6rk/1/
var drag = true;
// makes any image resizable on the page
$(function() {
$("img").resizable();
});
// Make the DIV element draggable
// Simple loop that goes through all element ids that start with 'dragId'
// (This needs to be the naming convention or this won't work)
var dragPrefix = 'dragId';
var el;
for (i = 0; el = document.getElementById(dragPrefix + i); i++) {
dragElement(el);
}
function dragElement(elmnt) {
var pos1 = 0,
pos2 = 0,
pos3 = 0,
pos4 = 0;
if (document.getElementById(elmnt.id)) {
// if present, the header is where you move the DIV from:
document.getElementById(elmnt.id).onmousedown = dragMouseDown;
} else {
// otherwise, move the DIV from anywhere inside the DIV:
elmnt.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
getToTop();
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
elmnt.style.opacity = "0.5"
getToTop();
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
elmnt.style.opacity = "1.0";
getToTop();
}
// Simple function that makes all other drag elements 1 and the one in 'focus' 5 which will make it
// hover over the other elements
function getToTop() {
for (i = 0; el = document.getElementById(dragPrefix + i); i++) {
el.style.zIndex = "1";
}
elmnt.style.zIndex = "5"
}
}
.drag_img {
position: absolute;
display: inline-block;
}
#mydiv {
position: absolute;
z-index: 9;
background-color: #f1f1f1;
border: 1px solid #d3d3d3;
text-align: center;
}
#mydivheader {
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Right now both resizing and drag is executing at the same time causing the conflict. I think your direction on the flag is correct but resizing has a threshold so the events start and stop will be delayed compared to drag thus drag still happens first. The best option is to bind to the resizing handles so that when the user is operating the resizer the drag is disabled.
Creating a flag whenever the user's mouse is down on the handlers:
$("#mydivheader").resizable({
create: function(e, ui) {
$('.ui-resizable-handle')
.on('mousedown', function() {
resizing = true;
})
.on('mouseup', function() {
resizing = false;
});
}
});
https://jsfiddle.net/jo9m2phb/1/

bring objects to front with zIndex javascript

I have a few draggable objects that are overlaying like a stack of papers.
I want each object to be lied on top of the stack when picked up.
I have been trying but somehow it is not properly working.
The closest I got was that every time I click one object I needed to click 1 extra time for at the next item until it reaches the front.
I guess its an easy fix but I fail to find it.
Thanks in advance.
dragElement(document.getElementById("drags"));
dragElement(document.getElementById("drags1"));
dragElement(document.getElementById("drags2"));
dragElement(document.getElementById("drags3"));
dragElement(document.getElementById("drags4"));
dragElement(document.getElementById("drags5"));
dragElement(document.getElementById("drags6"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
var z_Index = 1;
elmnt.onmousedown = dragMouseDown;
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
elmnt.style.zIndex = z_Index;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
/* stop moving when mouse button is released:*/
document.onmouseup = null;
document.onmousemove = null;
z_Index++;
}
}
#drags, #drags1, #drags2, #drags3, #drags4 {
position: absolute;
width: 50px;
height: 50px;
}
#drags{
background-color: red;
left:34%;
top:12%;
}
#drags1{
background-color: blue;
left:61%;
top:14%;
}
#drags2{
background-color: green;
left:22%;
top:18%;
}
#drags3{
background-color: yellow;
left:35%;
top:29%;
}
#drags4{
background-color: black;
left:40%;
top:20%;
}
<body>
<div id="drags"></div>
<div id="drags1"></div>
<div id="drags2"></div>
<div id="drags3"></div>
<div id="drags4"></div>
<div id="see-also">Footer</div>
</body>

Categories