Drag n Drop using JavaScript - javascript

I have begun to learn JavaScript. I have tried the following to drag and drop an image into a dropzone called "dropTarget1"; the image is not draggable. Can you please take a look at my code and advise what I am doing wrong.
var draggable=document.getElementById('dragMe1');
draggable.addEventListener('dragstart',dragStart,false);
var droptarget=document.getElementById("dropTarget1");
droptarget.addEventListener('dragenter',dragEnter,false);
droptarget.addEventListener('dragover',dragOver,false);
droptarget.addEventListener('dragleave',dragLeave,false);
droptarget.addEventListener('drop',drop,false);
function dragStart(event){
event.dataTransfer.setData('text/html', event.currentTarget.id);
}
function dragOver(event) {
event.preventDefault();
return false;
}
function drop(event) {
var dragMe1=document.createElement("img");
var data = event.dataTransfer.getData('text/html');
event.preventDefault();
event.stopPropagation();
dragMe1.src=data;
droptarget.appendChild('dragMe1');
return false;
}
#dropTarget1{
width:300px;
height:300px;
background-color:#DBF272;
}
#dragMe1{
width:300px;
}
#dragMe1 img{
padding-left:45px;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<link href="myStyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="dropTarget1"></div>
<img id="dragMe1" src="logo1.png" draggable="true" >
<script src="myDragnDrop.js"> </script>
</body>
</html>

If you want to use jQuery, then this Draggable|jquery UI can be a really simlple option.

Your JavaScript code should be like this (Explanation in the comments);
var draggable=document.getElementById('dragMe1');
var droptarget=document.getElementById("dropTarget1");
var newIm = document.createElement("img"); //Create new image element
/*Subscribe to dragover event.
This event fires when a user drag the image over the target */
droptarget.addEventListener('dragover',dragOver,false);
/*Subscribe to drop event.
This event fires when a user drop the image on the target */
droptarget.addEventListener('drop',drop,false);
function dragOver(event) {
event.stopPropagation(); //Prevent further drop events from bubbling up the DOM tree
event.preventDefault(); //Prevent the default behavior of the browser when dropping something on it
event.dataTransfer.dropEffect = "move"; //Specify the feedback that the user receives when a user drags over the target. It can be copy, link, or none
return false;
}
function drop(event) {
var data = event.dataTransfer.getData('text/plain'); //To retrieve the image URL
event.preventDefault();
event.stopPropagation();
newIm.src=data; //Write the image URL into the src attribute of newIm
droptarget.appendChild(newIm); //Add the new created image to the target element
document.body.removeChild(draggable); //Remove the original image as you're dragging and dropping (moving)
return false;
}
You don't have to subscribe to some events like dragenter, you just need to subscribe to dragover and drop events.

Related

Jquery Anchor Tag Doesnt open a poup

I am trying to do 2 things:
Open a popup when someone clicks on Lease today (Please note I do not have control over the HTML, so Jquery is the only way to change the HREF)
Change the Anchor tag back to "/floor-plans.aspx" after the first click
Somehow the code is not calling the function at all and not sure how to do #2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Change HREF Attribute of Anchor Tag </title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('a[href^="http://"]').each(function(){
var oldUrl = $(this).attr("href"); // Get current url
var newUrl = oldUrl.replace("/floor-plans.aspx", "openPopup()"); // Create new url
$(this).attr("href", newUrl); // Set herf value
});
});
function openPopup(){
alert("popupopened");
}
</script>
</head>
<body>
<span>Lease Today</span>
</body>
</html>
There are two parts to this, the first click to do the alert, then the second to NOT do the alert but allow the click (and turn off this handler, first time only we alert)
In addition, I added a class to make the selector much simpler to use/understand.
You did not ask how to tell what was clicked in the function, so I show that as well as how to pass some extra values/objects.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Change HREF Attribute of Anchor Tag </title>
</head>
<body>
<span>Lease Today</span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function openPopup(event,passed) {
console.log(passed.foo.Name);
alert("popupopened was "+$(event.target).text());
}
$(function() {
$('a.replacer-clicker').on('click', function(event) {
// Get prior url if we had it
let prior = $(this).data('prior-href');
if (!prior) {
// do not go there and stop other event handlers from seeing it
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
// save old, no prior click
$(this).data('prior-href', $(this).attr("href"));
// all it with this instead so we know context of it
openPopup.apply(this, [event,{foo:{Name:"fooby"}}]);
// simple
//openPopup();
} else {
console.log(prior);
//second click (had prior)
// now turn this handler off
$(this).off('click');
// now re-trigger the click, pass some arguments
$(this).trigger('click',[{foo:{Name:"fooby"}}]);
}
});
});
</script>
</body>
</html>
Your first issue is hwo you select the anchor and the second one is related on how you use href attribute.
Fixed code:
function openPopup(){
alert("popupopened");
}
$('a[href^="/floor-plans.aspx"]').each(function(){
var oldUrl = $(this).attr("href"); // Get current url
var newUrl = oldUrl.replace("/floor-plans.aspx", "javascript:openPopup();"); // Create new url
$(this).attr("href", newUrl); // Set herf value
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Lease Today</span>
The correct way is:
$('a[href^="/floor-plans.aspx"]').on('click', function(e) {
e.preventDefault();
alert("popupopened");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Lease Today</span>
Instead, if the html element is not yet ready you can delegate the click event:
$(document).on('click', 'a[href^="/floor-plans.aspx"]', function(e) {
e.preventDefault();
alert("popupopened");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Lease Today</span>

Chrome drag drop file/folder not working

I am trying to create PoC for Drag and drop a folder onto Chrome (v46) with the below code but alert is not getting triggered. Chrome switches to the folder browser view when a folder is dropped or opens the dragged file as it is dropped. Basically it keeps the default behavior. I tried to open the html file like "http://localhost/index.html" and "file:///C:\index.html" but both behave the same.
Where am I going wrong?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Drop File/Folder</title>
</head>
<body>
<div id="dropzone" style="border: solid 1px; padding: 200px;">Drop files or folders here</div>
<script type="text/javascript">
var dropzone = document.getElementById('dropzone');
dropzone.ondrop = function (e) {
alert("dropped!");
e.preventDefault();
};
// I also tried this but no success
//dropzone.addEventListener('drop', function (e) {
// alert("dropped!");
// e.preventDefault();
//});
</script>
</body>
</html>
It turns out you need to add a dragover handler.
dropzone.ondragover = function (e) {
e.preventDefault();
};

How do I programmatically trigger "hoverintent" on an element

I am using Tristen Brown's hoverintent library, which is a pure Javascript version of the jQuery hoverIntent library.
I have two elements first and second.
The second element has hoverintent handlers which causes a tooltip to appear above that element. When I manually hover over second, the tooltip appears as expected.
I would like to trigger the tooltip of second programmatically. For example, to make interacting with the first element cause the tooltip of the second element to appear. I have attempted to do this using jQuery trigger. I am able to trigger mouseover handlers, but not any hoverIntent.
Any suggestions?
Here is my Javascript:
$( document ).ready(function() {
var first = document.getElementById('first');
var second = document.getElementById('second');
$(first).mouseover(function(){
$(second).trigger({ type:"mouseover", clientX:"350", clientY:"105" });
$(second).trigger({ type:"mousemove", clientX:"350", clientY:"105" });
});
hoverintent(second, function(e) {
this.className = 'on';
}, function(e) {
this.className = 'off';
});
$(second).mouseover(function(){
console.log("mouseover");
});
});
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src='http://tristen.ca/hoverintent/dist/hoverintent.min.js'></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div style="padding:100px;">
<ul class='examples'>
<li id='first'>
Trigger
</li>
<li id='second'>
hoverintent
<span class='popup'>Hi there</span>
</li>
</ul>
</div>
</body>
</html>
The full JS bin is here:
http://jsbin.com/kumeva/4/edit?js,output
I would like to trigger the tooltip of second by mousing over the first element.
You can dispatch a sequence of mouse events to #second and keep the hoverintent code and the dispatch code completely separate like this:
// Hoverintent code
$(document).ready(function() {
var second = document.getElementById('second');
hoverintent(second, function(e) {
this.className = 'on';
}, function(e) {
this.className = 'off';
});
});
///////////////////////////////////
// Dispatch code
$(document).ready(function() {
var first = document.getElementById('first');
var second = document.getElementById('second');
$(first).on("mouseover", function(){
// Send a mouseover to wake hoverintent
var event = new MouseEvent("mouseover");
second.dispatchEvent(event);
// Send a mousemove trigger the internal hover code
event = new MouseEvent("mousemove");
second.dispatchEvent(event);
});
$(first).on("mouseout", function(){
// Cancel the hover code
var event = new MouseEvent("mouseout");
second.dispatchEvent(event);
});
});
Demo
According to the source code of the librairy, it seam that it rely on mouseover and mouseout. To determine the mouse position, it seam to use clientX and clientY, not pageX/Y.
Source file : https://github.com/tristen/hoverintent/blob/gh-pages/index.js

prevent all MouseClick event until page load

I have a situation in which i have to prevent all MouseClick events until the page loads.
i have 1 javascript function defined on page load like
onload="init();"
Now in function init(), we are showing tree and select a particular node of it.
function init() {
ExpandAncestors(node);
ExpandNode(node);
setTimeout("treeScrollToView()", 1000);
}
Now i want to prevent all the mouse click event on tree/page until whole tree is not fully shown.
I have searched through some of the posts related to my question but that uses event.preventDefault() but i dont have Event object here.
Any help is greatly appreciated.
You can use:
CSS
body {
pointer-events:none;
}
and then on page load reactivate them
$(document).ready(() => {
$('body').css('pointer-events', 'all') //activate all pointer-events on body
})
Explanation
pointer-events:none; blocks all mouse interaction with the elements it's applied to - Since the body is usually the parent of all the elements in your page, it would case them not to react to any mouse interaction at all.
Keep in mind that all mouse interaction would be blocked this way, not only mouse clicks but mouse hover, mouse up's etc etc..
I think the basic need is to prevent user from clicking the tree area. I would prefer to display an overlay div rather than playing with the tree mouse click events.
You can show a loading overlay on the tree part until it is loaded. once done, you can hide the loading and show your original tree.
Ref: How to completely DISABLE any MOUSE CLICK
JavaScript Only
You can have an event listener along with a boolean. onclick disables a click. oncontextmenu disables right clicks.
(function(){window.onload = function () {
var allowClicks = false;
document.onclick = function (e) { !allowClicks&&e.preventDefault(); }
document.oncontextmenu = function (e) { !allowClicks&&e.preventDefault(); }
document.getElementById('myElement').onload = function () { allowClicks = true; }
}());
myElement is your element which you can replace with whatever
Use this with one element
If you want to disable mouse clicks for just one element, do:
(function(){window.onload = function () {
var allowClicks = false,
elem = document.getElementById('myElement');
elem.onclick = function (e) { !allowClicks&&e.preventDefault(); }
elem.oncontextmenu = function (e) { !allowClicks&&e.preventDefault(); }
elem.onload = function () { allowClicks = true; }
}());
onload="init();" here you can have event object.
pass event as argument.
onload="init(event);"
now you can use that in init() function.
Try utilizing $.holdReady()
$.holdReady(true);
$(window).off("click");
$("*").each(function(i, el) {
this.onclick = function(e) {
e.preventDefault();
}
});
function init() {
$("div").on("click", function() {
alert($.now())
})
}
setTimeout(function() {
$.holdReady(false);
}, 7000)
$(function() {
init()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body>
<div>click</div>
click
</body>

How to exclude div from firing this event?

I use code bellow to get the text that user has double clicked:
<html>
<script language="javascript">
document.ondblclick = function() {
alert(GetSelectedText());
}
function GetSelectedText() {
if (document.selection) {
return document.selection.createRange().text;
}
}
</script>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>
<div id="should_trigger_event">sample of a text!</div>
<div id="should_not_trigger_event">sample of a text!</div>
</body>
</html>
I want to ondblclick event just fire up for div with id: should_trigger_event and not for div with id: should_not_trigger_event
How can we achieve that?
It is simple using jQuery :
<script language="javascript">
$(document).ready(function(){
$('#should_trigger_event').on('dblclick',function(){
alert(GetSelectedText());
});
});
function GetSelectedText() {
if (document.selection) {
return document.selection.createRange().text;
}
}
</script>
More Information on
jQuery Selectors
jQuery double click binding
Why dont you bind click event using element id:
$(function(){
$('#should_trigger_event').click(function(){
if (document.selection) {
return document.selection.createRange().text;
}});});
You can directly assign the handler to the div you want to include…
var div = document.getElementById('should_trigger_event');
div.ondblclick = function() {
alert(GetSelectedText());
}
or if you want the handler for whole document, you can check target in event object
document.ondblclick = function(e) {
if(e.target.id != 'should_not_trigger_event')
alert(GetSelectedText());
}

Categories

Resources