Add HTML Dynamically on Drag N Drop - javascript

A simple way to drag and drop html elements or content on a web page?
The goal is to drag the element and drop it on a container.
Once the element is dropped it will dynamically add html content based on its id.

To begin you will need to create an html page with the following code.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Drag N Drop Elements</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<!-- The element to be dragged and dropped -->
<span class="elements" id="paragraph">|Paragraph|</span>
<!-- The target for the dragged elements -->
<div id="document-section">This is the target for the drag n drop.</div>
<!--import javascript-->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
<script src="dragndrop.js"></script>
</body>
</html>
The following html in the example above is the element that you will be able to drag once completing all the javascript is added later on.
<span class="elements" id="paragraph">|Paragraph|</span>
Note: You can add other draggable elements by giving them the class elements and assigning a different id.
The next important element to discuss is the area on the page where the draggable elements are going to be dropped. To allow elements to be dropped in this area I have assigned it the id of #document-section that you will see used in the javascipt example later on.
Note: You don't have to use text in the div element below but make sure it has some width, height, and a border so that the user can see where to drop the element.
<div id="document-section">This is the target for the drag n drop.</div>
Next you will need to create a javascript file named dragndrop.js and place it in the same folder as the html file you created in the first step.
Javascript:
//store the id of the item being dragged
var dragging;
/*make all of the elements draggable*/
$(".elements").draggable({helper:"clone"});
/*on dragstart event for .elements*/
$(".elements").on("dragstart",function(){
//get the id of the element being dragged
dragging = $(this).attr("id");
});//end on dragstart event for .elements
//fire event when an element is dropped on #document-section div
$("#document-section").droppable({//begin droppable event
drop: function(event,ui) {//begin drop function
//switch case statement used to detect what element has been dropped
switch(dragging){//begin switch case
case "paragraph":
//array to hold the paragraph
var paragraph = [];
//if dragging variable equals "paragraph"
if(dragging === "paragraph"){//begin if then
//add the paragraph
paragraph.push('<p>Hello, I am a paragraph</p>');
//append the paragraph to your container I used #document-section in this example
$("#document-section").append(paragraph.join(""));
//set dragging to null to prevent duplicate elements being creating on drop
dragging = null;
break;
}//end switch case
}//end if then
}//end drop function
});//end droppable event
Once finished you should be able to drag the "paragraph" text on to the "This is the target for the drag n drop.", and see the results.

Related

When click element it appear elsewhere javascript/jquery

I need a JavaScript / jQuery code that will allow me when I click one of the elements "A" or "B" to appear in a place (span tags).
It's basically a selection and a display of that selection, when i click element "B", in the span tag should appear "B", if click on "A" then element "A" will appear in the span tag.
<!-- Where should be displayed elements A or B -->
<span>...</span>
<!-- The elements to click on -->
<h1>A</h1>
<h1>B</h1>
use click event and text.
$('h1').click((e) => { $('span').text($(e.target).text());})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>...</span>
<h1>A</h1>
<h1>B</h1>
Possible solution with pure Javascript could be:
const headings = document.querySelectorAll('.heading');
const result = document.querySelector('#result');
headings.forEach(heading => {
heading.addEventListener('click', () => {
result.innerText = heading.innerText;
});
});
It's good to identify the elements on the page somehow, here I placed an id = "result" on the span element, and class = "heading" to both headings A and B (you could also select those elements with document.getElementsByTagName when you haven't got any better identifiers like classes and IDs). I grabbed the elements from the DOM and stored them in variables. Then you just loop through the headings and add click event listeners to them, on the click you take the innerText from the clicked heading and place it as innerText into the span.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<!-- Where should be displayed elements A or B -->
<span>...</span>
<!-- The elements to click on -->
<h1>A</h1>
<h1>B</h1>
<script>
/**
* Quick solution without changing the html markup
* could be something like this. But it could be
* improved with better markup thus there could be
* better structured script. It's pure JS.
*/
// Select the element where the value of selection
// should be outputed.
const output = document.querySelector('span');
// Select all elements that are considered an option.
const variant = document.querySelectorAll('h1');
// Elements are in array, so you need to loop through
// them. For loop performs better than forEach.
// We need some counter, we name it i, but you can
// name it anything you want. Arrays are 0 indexed,
// so we assign the initial value 0. Next we need
// a condition, how long should the loop run.
// So as long it’s less than count of variants,
// perform the actions. Last in the for loop is
// what should happen after sequention, we increment
// our counter i by one, alternative of i++ could be
// i += 1.
for (let i = 0; i < variant.length; i++) {
// We take variant[i] - starting from 0 to 1 and then
// we add event listener, that listens for clicks.
// After variant is clicked, we pass an anonymous
// function.
variant[i].addEventListener('click', () => {
// This function simply takes the inner text
// of variant and makes it inner text of
// the output.
output.innerText = variant[i].innerText;
});
}
</script>
</body>
</html>

How to find earlier element by partial id

I trying to find the parent div of a clicked item but can only get it working by manually setting the div id. There are many similar divs with incrementing id's
<div id="grid0"...
<div id="grid1"...
<div id="grid2"...
etc
My javscript is as follows but this only finds the first grid
function popUp1HtmlContent(e) {
var dataItem = $("div[id^=grid]").data("kGrid").dataItem(e.target.closest("tr"));
var content = dataItem.PopUp1Html;
return content;
}
How do I find the parent div in this function?
Eg setting this manually works for each grid
var dataItem = $("div[id=grid0]").data("kGrid").dataItem(e.target.closest("tr"));
var dataItem = $("div[id=grid1]").data("kGrid").dataItem(e.target.closest("tr"));
etc
Is there a way to search back through the parents to find the first matching div with id starting "grid{0}"?
The event fires from an image within a td element. Also it's not always the direct parent but can have varying number of elements between clicked element and div I'm trying to locate.

Make element draggable when child element is dragged

I have multiple programmatically created span elements designed to look and act like windows. Each element has a title bar running across the top. I am trying to get it so that the draggability is activated either by or only if the mouse is over the child title element using jQuery UI, is this possible?
It's possible. When the mouse hold the child element, make the parent element draggable, then make it not draggable again when mouse realizes it.
// The parent element
var $aa = $("#aa"),
// The child element
$bb = $("#bb");
// When the mouse is down
$bb.mousedown(function() {
// Drag the element
$aa.draggable();
});
// When the mouse realizes
$bb.mouseup(function() {
// Don't drag the element
$aa.draggable('destroy');
});
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js" integrity="sha256-xI/qyl9vpwWFOXz7+x/9WkG5j/SVnSw21viy8fWwbeE=" crossorigin="anonymous"></script>
<div id="aa">
---
<div id="bb">Push me</div>
</div>
This could improve with more events, anyway.

How to get id of an element when clicked on it - javascript

I am developing a canvas application on which a user can draw various shapes. Various elements are drawn using d3.js. I want to use jsplumb to connect two SVG elements for which I need the id of each element when it is clicked on. Each element has an id that is generated by code when it is drawn and thus I don't know it before hand.
Is there a javascript implementation by which I can get the id of the elements on which I click? I wouldn't preferably want to add '' on each element that is being drawn on the canvas.
Can anyone suggest a way to do this?
You can use something like this
<script type='text/javascript'>
doClick = function (sender){
alert(sender.id);
}
</script>
<div id='a1' onclick='doClick(this)'>div1</div>
<div id='a2' onclick='doClick(this)'>div2</div>
https://jsfiddle.net/dy47dbvp/3/
You can simply access an element's ID using that element's attributes
var elemID = droppedElement.attr('id');
To get the id of the clicked Element:
$('#container').on('click', '.droppedElement', function (e) {
var elemID = droppedElement.attr('id');
}
The container is your canvas id and the droppedElement is the variable that captures the svg element or the clone of the svg element(if that is your case)

Onclick on different DIV tags

I have two DIV tags.
1) Green Color is outer Div Tag which has onclick property set to alert('Clicked').
2) Yellow Color is Inner DIV Tag
Now, when I perform a click on inner div tag an alert pops up. Same repeats while selecting items from inner div tag. I'm not able to select in the inner div tags. How can this be resolved?
Further more, I will have nested div tags which are generated dynamically. I'm stuck here
You need to prevent the propagation of your click up to the outer div.
Sorry about the repost, but the answer is already located at:
event.preventDefault() vs. return false
One solution is to set an event listener on your outer container, and, when the listener is triggered, only act after you have verified that the click did not originate from any of the container's children (in this case, inner). You could tweak this solution to only exclude specific children by class, id, etc:
$(document).ready(function() {
var outer = $('.outer');
outer.on('click', handleOuterClick);
function handleOuterClick(e) {
//Assert that the click originated from the outer div, and not from
//any of its children
var origin = e.target,
children = outer.children();
if(children.index($(origin)) == -1) {
//Proceed by displaying an alert
alert("You clicked the outer div!");
}
};
});
Here's the fiddle: http://jsfiddle.net/39ssk/
Check this out. You can apply id, and use those ids to control onclick.
<html><head></head>
<body>
<script type="text/javascript">
function manualToggle(val)
{
alert(val.id);
}
</script>
<div id="test" onclick="manualToggle(this);">
<span>Allowed to click</span>
<span onclick="event.cancelBubble=true;if (event.stopPropagation) event.stopPropagation();">Not allowed to click</span>
<span>Allowed to click</span>
</div>
</body>
</html>

Categories

Resources