Detect MouseUp while something is following the cursor - javascript

I have been working on a online file system and I want to have users be able to drag and drop files to a new location. I don't really like how the default drag and drop visuals look so I am not using the conventional methond. This is what I have so far.
This code is in a .php file which is loaded onto the main page with jQuery
<td draggable = "true" ondragstart="dragFolder(event, \''.$folderId.'\', \''.$folderName.'\')">
<div class = "single-folder" onMouseUp = "folderDropUp(event, \''.$folderId.'\');">
<div class = "single-folder-name" id = "single-folder-name-'.$folderId.'">
<span id = "single-folder-rename-'.$folderId.'" class = "rename-folder-hover">
'.$folderName.'
</span>
</div>
</div>
</td>
Here is the dragFolder function that I have being fired from "ondragstart".
function dragFolder(e, folderId, folderName) {
var posX, posY, clicked, isDown = false;
var newFolder;
document.getElementById("folder_drag_image").setAttribute("folderId", folderId);
$(".single-folder").mousedown(function() {
clicked = true;
isDown = true;
followCursor(event);
});
$(document).mouseup(function() {
clicked = false;
$('#folder_drag_image').hide();
if(isDown){
//dropOnFolder(event, document.getElementById("folder_drag_image").getAttribute("folderId"), )
isDown = false;
}
});
$(document).mousemove(function(e) {
if(clicked == true) {
$('#folder_drag_image').show();
$('#folder_drag_image').stop(true, true);
followCursor(event);
}
});
function followCursor(e) {
clicked = true;
posX = e.pageX;
posY = e.pageY;
$('#folder_drag_image').animate({left: posX, top: posY});
}
}
function folderDropUp(e, newFolderId) {
alert(newFolderId);
isDown = true;
}
Basically what it does is it does is when the mouse goes down over a folder div it shows a fake dragging folder with the id of "folder_drag_image" which follows the mouse until the mouse goes up.
The problem comes here when I want to release the folder ontop of the new folder it will be put in. Here is the function for that.
function folderDropUp(e, newFolderId) {
alert(newFolderId);
isDown = true;
}
I took out the ajax because that is not part of the problem. If you look back up the the first code snippet there is a "onMouseUp" listener which triggers a "folderDropUp" event.
The problem is that if I drag my mouse onto folder with the fake drag image the folderDropUp function does not fire. If I just drag my mouse from anywhere else and it does not have the fake drag image when the function will fire off.
I did try jQuery mouseup function but just got the same output.

I don't know how helpful this will be, but by using jQueryUI you could do something like this:
HTML:
<html>
<head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css"/>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
</head>
<body>
<table>
<tr>
<td>
<div class="single-folder">
<div class="single-folder-name" id="single-folder-name-nhaca">
<div id="single-folder-rename-nhaca" class="rename-folder-hover">
<div>Folder 1</div><div class="folder-drag-image" id="nhaca-drag-image">Folder 1</div>
</div>
</div>
</div>
</td>
<td>
<div class="single-folder">
<div class="single-folder-name" id="single-folder-name-other">
<span id="single-folder-rename-other" class="rename-folder-hover">
<div>Folder 2</div><div class="folder-drag-image" id="other-drag-image">Folder 2</div>
</span>
</div>
</div>
</td>
</tr>
</table>
</body>
</html>
CSS:
.single-folder{
border: 1px solid black;
cursor: pointer;
width: 60px;
}
.folder-drag-image{
position: absolute;
height: 20px;
width: 60px;
border: 1px solid black;
display: none;
}
.droppable-ready-to-receive{
background-color: yellow;
}
JS:
$( document ).ready(function() {
//displaying draggable element based on hovered element
$(".single-folder").on("mouseenter", function(e){
var drag_image = $(this).find(".folder-drag-image");
drag_image.css({"display": "block", "top": $(this).offset().top + 20, "left": $(this).offset().left});
});
//resetting draggable element when moving outside the "single-folder" div
$(".single-folder").on("mouseleave", function(e){
var drag_image = $(this).find(".folder-drag-image");
drag_image.css("display", "none");
});
//resetting draggable element when not being dragged any longer
$(".folder-drag-image").draggable({
stop: function(e) {
var parent = $(this).parents(".single-folder");
$(this).css({"display": "none", "top": parent.offset().top, "left": parent.offset().left});
}
});
//defining what elements can be dropped and what to do when dropped
$(".single-folder").droppable({
accept: '.folder-drag-image',
hoverClass: "droppable-ready-to-receive",
drop: function(e, ui) {
console.log("Dropped folder " + ui.draggable.text() + " into " + $(this).find(".folder-drag-image").text());
//handle folder drop however you need from here
}
});
});
EXAMPLE:http://jsfiddle.net/skdfLk5b/3/
I'm guessing this is far from a good solution to this, but hopefully it helps somehow.

Related

When scrolling flashing background color

My code is to apply div background-color when user touchstart on each div. that's clear for you.
Then when user scrolling, I use $(window).scroll.. event to reset or remove background-color for all div's.
But my problem is: when user (touch + scrolling) at div's, background-color is flashing out color! I want to: don't change div background-color when (tap, touch + scrolling). if you don't understand my question, you can see: (facebook messenger friend conversations, snapchat conversations, stories ..etc)
Flashing div's:
My code: https://www.w3schools.com/code/tryit.asp?filename=GLUIAUU64MDX - RUN ON TOUCH DEVICES.
$(window).scroll(function() {
resetBg();
});
$(".❄").on('touchstart', function() {
$(this).css("background-color", "#7bffea");
});
$(".❄").on('touchend mouseleave mouseup blur click', function() {
resetBg();
});
function resetBg() {
$(".❄").css("background-color", "");
}
div.❄ {
display: block;
height: 150px;
border: 1px solid black;
margin: 10px 0px;
padding: 0px;
border-radius: 8px;
background-color: #ffffff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
<div class="❄"></div>
Instead of setting background on touchstart, you can get the pointer position at touchstart and on touchend check if pointer position is changed or not. If not, change the div background and set a timeout function to reset it. If the position of pointer is changed then it's a scroll so you don't need to change the background
let initialY = null;
$(".❄").on('touchstart', function(e) {
initialY = e.clientY;
});
$(".❄").on('touchend', function(e) {
if(e.clientY===initialY){
$(this).css("background-color", "#7bffea");
setTimeout(()=>{ //This is optional
resetBg();
},100);
}
});
function resetBg() {
$(".❄").css("background-color", "");
}
try this
$(window).scroll(function() {
resetBg();
});
//----------------------------------------------
$(document).on('touchstart', '.❄', function(evt) {
var that = this;
var oldScrollTop = $(window).scrollTop();
window.setTimeout(function() {
var newScrollTop = $(window).scrollTop();
if (Math.abs(oldScrollTop - newScrollTop) < 3) $(that).css("background-color", "#7bffea");
}, 200);
});
$(".❄").on('touchend touchmove mouseleave mouseup blur click', function() {
resetBg();
});
function resetBg() {
$(".❄").css("background-color", "");
}

Change element CSS when a div is visible [duplicate]

This question already has answers here:
Remove CSS from a Div using JQuery
(13 answers)
Closed 7 years ago.
How to remove a CSS line of code when a certain div is reached?
Please note:
I need the CSS class that contains this line of code
The div is reached by clicking a link in the page header so I think mouseenter() event is not enough.
My Code:
$(document).ready(function(){
//firing the event to change CSS when reaching #resume
$('#resume').mouseenter(function() {
$('#resume').class('education').css('border-bottom','');
});
});
.education, .work {
margin-bottom: 48px;
padding-bottom: 24px;
//border-bottom: 1px solid #E8E8E8;
}
<section id="resume">
<!-- Education -->
<div class="row education">
<div class="three columns header-col">
<h1><span>Education</span></h1>
</div>
<div class="education work">
</div> <!-- main-col end -->
</div> <!-- End Education -->
When reaching #resume, you mean by scrolling? Then you need to use $(window).scroll() function / event:
$(function () {
// To change on scroll and reach `#resume`.
$(window).scroll(function () {
if ($(window).scrollTop() > $("#resume").offset().top)
$('#resume').addClass('education').css('border-bottom', '0');
});
// To change when hovering.
$('#resume').mouseenter(function () {
$(this).addClass('education').css('border-bottom', '0');
$(this).find(".education").css('border-bottom', '0');
});
});
just use the class name
$(document).ready(function(){
// firing the event to change CSS when reaching #resume
$('#resume').mouseenter(function(){
$('.education').css('border-bottom','');
});
The answer is on assumption that the class is already set on the element, and you just want to remove the border-bottom.
$(document).ready(function(){
//firing the event to change CSS when reaching #resume
$('#resume').mouseenter(function(){
//You can use 'this' as it is in the context of this element
//It will look inside the context element, then find all elements with class "education" and set the border-bottom to none.
$(this).find(".education").css({'border-bottom' : 'none'});
});
});
You could remove your class and add a new class containing the right css.
$(this).removeClass('someClass');
$(this).addClass('someClass');
Otherwise you could do something like this:
$(this).css({'border-bottom' : ''});
You can use 'this' when it is in the context of the element
$(document).ready(function() {
var Bind = function(elem, event, func) {
elem[window.addEventListener ? 'addEventListener' : 'attachEvent'](window.addEventListener ? event : 'on' + event, func, false);
},
scrollPos = function() {
var doc = document.documentElement;
return {
'left': (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0),
'top': (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0)
};
},
tgtOffset = document.getElementById('tgt').offsetTop,
scrolled = false,
spotted = function() {
var dist = tgtOffset - scrollPos().top,
adj = window.innerHeight > (480 / 2) ? window.innerHeight : 100;
return dist > -100 && dist < adj;
},
inView = null;
var res = document.getElementById('resume');
Bind(window, 'scroll', function(event) {
clearTimeout(inView);
if (!scrolled && spotted()) {
inView = setTimeout(function() {
res.classList.add('education');
});
}
});
});
.education,
.work {
margin-bottom: 48px;
padding-bottom: 24px;
// border-bottom: 1px solid #E8E8E8;
}
<section id="resume">
<!-- Education -->
<div class="row education">
<div class="three columns header-col">
<h1><span>Education</span></h1>
</div>
<div class="education work">
</div>
<!-- main-col end -->
</div>
<!-- End Education -->

How can one append a div exactly in the position where the mouse is over? jQuery

I want to leave a colored div trail without generating divs when the page loads. I want them to be appended when the mouse is over the parent div and position them where the mouse is within it.
EDIT: I think I need to be more precise so I posted the code that I want to rewrite. I want it to do the same thing without generating the divs that become colored on mouseover when the page loads but to create a colored div when the mouse is over $(".container") at the current position of the mouse.
THANKS!
Mention: the script generates lots of divs - it might take a while for the page to load.
$(document).ready( function() {
var csize = $(".container").width() * $(".container").height();
var space = $(window).width() * $(window).height();
while ( csize * $(".container").length < space) {
$("#space").append("<div class='container'></div>");
};
$(document).on("mousemove", function() {
window.color = Math.floor(Math.random()*16777215).toString(16);
});
$(".container").on("mouseover", function() {
$(this).css("background-color", "#" + window.color);
});
});
#space{
width: auto;
height: auto;
}
.container {
width: 15px;
height: 15px;
display: inline-block;
float: left;
border: none;
}
<!DOCTYPE html>
<html>
<head>
<title> JqPractice</title>
<link rel="stylesheet" type="text/css" href="reset.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="jq.js" type="text/javascript"></script>
<script src="sv2.js" type="text/javascript"></script>
</head>
<body>
<div id="space">
<div class="container">
</div>
</div>
</body>
<footer>
</footer>
</html>
$("#parent").on({
mousemove: function (e) {
var wrapper = $(this);
var parentOffset = wrapper.offset();
var relX = e.pageX - parentOffset.left + wrapper.scrollLeft();
var relY = e.pageY - parentOffset.top + wrapper.scrollTop();
wrapper.find('.randomTrail:visible').remove();
wrapper.append($('<div class="randomTrail"/>').css({
left: relX,
top: relY
}));
},
mouseleave: function () {
$('.randomTrail:visible').remove();
}
});
DEMO
Ref:
.offset()
.scrollLeft()
.scrollTop()
.remove()
e.pageX and e.pageY
.on()
mousemove
mouseleave
Events
find()
You will need to use mousemoves() to get the event data and coordinate like below
$( "#target" ).mousemove(function( event ) {
var msg = "Handler for .mousemove() called at ";
msg += event.pageX + ", " + event.pageY;
console.log(msg);
});
and you will need a div with css {position:absolute; width:10px; height:10px; background-color:yellow; left: event.pageX; top:event.pageY} something like this will do
For more info checkout official doc from jQuery

How to allow text selection in an element that has a canvas overlay (issue with IE9 non-support of pointer-events=none)

I have been looking for a solution for the lack of support for the pointer-events property in IE9/10. There are a couple of other related posts here:
css 'pointer-events' property alternative for IE
How to make Internet Explorer emulate pointer-events:none?.
And I can forward mouse events such as mousedown, up & move. But my real problem is how to get text selection to work - how to be able to select text that are in elements beneath the canvas.
In the example I have below, I use document.elementFromPoint with the coordinates from the event in order to find the element beneath the canvas to forward the event to. But that doesn't work for events such as selectstart because there is no coordinate information in the event. It also doesn't work for mousein/out because those events only fire on the canvas edge. As I said, mousemove works, but working with that event doesn't allow me to select text.
Has anyone found a solution for this, or have suggestions?
<!DOCTYPE html>
<head>
</head>
<body>
<div id="div" style="background-color: pink; width: 500px; height: 500px; position: absolute;">
<span style="background-color: yellow; position: absolute; left: 0px">Test 1</span>
<span style="background-color: red; position: absolute; left: 50px">Test 2</span>
<span style="background-color: blue; position: absolute; left: 100px">Test 3</span>
<span style="background-color: green; position: absolute; left: 150px">Test 4</span>
<span style="background-color: purple; position: absolute; left: 200px">Test 5</span>
<canvas id="canvas" style="background-color: gray; position: absolute; width: 100%; height: 100%; opacity: .5;">The canvas</canvas>
</div>
<script type="text/javascript">
var main = document.getElementById("div");
var canvas = document.getElementById("canvas");
var forwardAnEvent = function(event){
var display = canvas.style.display;
canvas.style.display = "none";
var bottomElement = document.elementFromPoint(event.clientX, event.clientY);
canvas.style.display = display;
var eventCopy = document.createEvent("MouseEvents");
eventCopy.initMouseEvent(event.type, event.bubbles, event.cancelable, event.view, event.detail,
event.pageX || event.layerX, event.pageY || event.layerY, event.clientX, event.clientY, event.ctrlKey, event.altKey,
event.shiftKey, event.metaKey, event.button, event.relatedTarget);
if (bottomElement)
bottomElement.dispatchEvent(eventCopy );
event.stopPropagation();
}
// Set event handlers on the canvas and forward to elements beneath.
// mouseover won't work because when the event happens on the canvas, there
// is nothing else under the mouse except the main div.
// Non-mouse events, such as selectstart, won't work because there is no
// coordinate information in the event to send to document.elementFromPoint.
// How can text selection work for the <span> elements beneath the canvas??
canvas.addEventListener("mouseover", function(event)
{
console.log("mouseover: " + event.target.innerHTML);
forwardAnEvent(event);
event.stopPropagation();
}
, false);
canvas.addEventListener("mousedown", function(event)
{
console.log("mousedown: " + event.target.innerHTML);
forwardAnEvent(event);
event.stopPropagation();
}
, false);
canvas.addEventListener("mouseup", function(event)
{
console.log("mouseup: " + event.target.innerHTML);
forwardAnEvent(event);
event.stopPropagation();
}
, false);
// Set event handlers on all of the <span> elements...
for (var i = 0 ; i < main.children.length; i++)
{
if (main.children[i].tagName == "CANVAS")
{
continue;
}
main.children[i].addEventListener("mouseover", function(event)
{
console.log("mouseover: " + event.target.innerHTML);
event.stopPropagation();
}
, false);
main.children[i].addEventListener("mousedown", function(event)
{
console.log("mousedown: " + event.target.innerHTML);
event.stopPropagation();
}
, false);
main.children[i].addEventListener("mouseup", function(event)
{
console.log("mouseup: " + event.target.innerHTML);
event.stopPropagation();
}
, false);
}
main.addEventListener("mouseover", function(event){
console.log("moving over div.");
event.stopPropagation();
}
, false);
main.addEventListener("mousedown", function(event){
console.log("mousedown div.");
event.stopPropagation();
}
, false);
main.addEventListener("mouseup", function(event){
console.log("mouseup div.");
event.stopPropagation();
}
, false);
</script>
</body>
</html>

Scroll the page vertically and scroll big image inside div horizontally on mouse drag with jQuery

I have page that I want to scroll vertically on event mouse down, and I already have found the answer on this question link. In my case i have a div that contain image that user put on it and sometimes it have bigger size than my div size, with overflow:auto; i get horizontal scroll inside that div. So i need to apply drag scroll horizontally on that div.
HTML
<html>
<body>
<div id="container">
<div class="detail-title"> TITLE </div>
<div class="detail-content">
<img src="...." />
!-- long content --!
</div>
</div>
</body>
</html>
CSS
.detail-main-content-box {
background: none;
display: block;
left: 0;
min-height: 350px;
overflow: auto;
padding: 5px 5px 5px 5px;
width: auto;
}
jQuery from answer link
$(document).on({
'mousemove': function (e) {
clicked && updateScrollPos(e);
},
'mousedown': function (e) {
clicked = true;
clickY = e.pageY;
$('html').addClass('block-selection').css({ 'cursor': 'url(../img/closedhand.cur), default' });
},
'mouseup': function () {
clicked = false;
$('html').removeClass('block-selection').css('cursor', 'auto');
}
});
var updateScrollPos = function(e) {
$(window).scrollTop($(window).scrollTop() + (clickY - e.pageY));
};
how can i apply this on div? i have try to change $(document) to $('.detail-content') also change function scrollTop to scrollLeft but nothing happen. Here is the fiddle for current condition.
this has been left here unanswered for two long years, not even a useful comment. OK, here is my try. hope it can help ( le roi est mort vive le roi)
<script type="text/javascript">
var clicked = true;
var clickY = e.pageY;
$('.detail-content').on({
'mousemove': function (e) {
clicked && updateScrollPos(this,e);
},
'mousedown': function (e) {
clicked = true;
clickY = e.pageY;
$('html').addClass('block-selection').css({ 'cursor': 'grabbing' });
},
'mouseup': function () {
clicked = false;
$('html').removeClass('block-selection').css('cursor', 'auto');
}
});
var updateScrollPos = function(obj,e) {
$(obj).scrollTop($(obj).scrollTop() + (clickY - e.pageY));
clickY = e.pageY;
};
</script>

Categories