I am trying to update a c3.js chart using drag and drops with dragula.js, but I don't know how to get the id of the div that is dragged into a new container. My html is something like this:
<div id="collapse1" class="panel-collapse collapse">
<div id="color1" class="form-inline">1</div>
<div id="color2" class="form-inline">2</div>
<div id="color3" class="form-inline">3</div>
</div>
<div id="collapse2" class="panel-collapse collapse">
</div>
and I'm using dragula.js to drag and drop:
dragula([collapse1,collapse2]);
I am really new to jquery, but following this question, to access the id of the <div> dropped into collapse2 in I was trying to do something like this:
alert($("#collapse1.collapse2 div:first").attr("id"));
But no results. Any help would be really appreciated
Dragula has three Elements One is Source Div, Target Div and Its associated Element. Following Method Works For Me as Charm except i am Not using get() method which has version issue.
You Can Try Both.
Dragula gives you the id of dropped div, Source Div, Target Div.
const dragula = Dragula(['', '']);
dragula.on('drop', (el, target, source, sibling) => {
const elementId = $(el).attr("id");
const targetID = $(target).attr("id");
const sourceId = $(source).attr("id");
}
Can't answer the question directly because I am not familiar with dragula. However, I have used jqueryUI drag drop extensively and its a really good tool. You might want to give that framework a try.
Since you asked for an example, I dug into some of my old code. You might want to go look through the jqueryUI draggable and droppable tutorials to give you some background before looking at this. I have included parts of a function. I put little dots to show you where code has been left out. I have put <<< next the key lines for you. Notice how I use closure to make references available across different parts. Closure is soooo awesome. I abuse the death out of it, so learn how to use it if you can.
Note that once I got my drag object, that is what you are asking for. Notice how I reference the variable to my function later when I register the draggable.
Btw, notice there is also a stop drag function referenced which I don't show the definition of. If you move the declaration of the dragObject outside of startDrag then you can also see it from stopDrag since the definition of the function is "enclosed" in the outside register function.
function tapeChart_registerDraggables(parentObject,scope) {
if ((parentObject==null)||(parentObject==undefined)) {
parentObject=$jq(document.body);
}
var availablesShow = false;
var savingToServer = false;
var dragClone = null;
var startDrag = function(event, ui) {
tapeChartDraggingReservation = true;
var dragObject = event.target; <<<<<<
if (dragObject.getAttribute("unassigned")=="true") {
var is_chrome = window.chrome;
var is_safari = navigator.userAgent.toLowerCase().indexOf('safari/') > -1;
if (!is_chrome && !is_safari) {
$(ui.helper).css("margin-left", event.clientX - $(dragObject).offset().left);
$(ui.helper).css("margin-top", event.clientY - $(dragObject).offset().top);
}
}
...
// assigned rooms
if (scope!="UNBLOCKED") {
// register items in the grid
$(parentObject).find( ".NODRAGHELPER" ).draggable(
{
snap : "true",
revert : "invalid",
start: startDrag, <<<<
stop: stopDrag
}
)
.click(function(){
if ( $(this).is('.NODRAGHELPER-dragging') ) {
return;
}
// seems that the user can drop and click fast
// prevent this
if (!savingToServer) {
tapeChart_getReservation(this);
}
return false;
});
}
...
Related
I have various elements that fire the same function. I need to be able to get the closet element of two different types of classes.
Before I would just have a function for each onClick event, though I want them to share the same one and instead just change the current_dragging_element to which ever element was closest to the two types of classes I am looking for.
current_dragging_element = event.target.closest(".draggable_list");
current_dragging_element = event.target.closest(".draggable_item");
async function onMouseDown(event) {
if (HANDLE THE CHANGE IN VAR?) {
current_dragging_element = event.target.closest(".draggable_list");
}
else {
current_dragging_element = event.target.closest(".draggable_item");
}
document.body.classList.add("noselect")
current_dragging_element.style.transform = "rotate(5deg)";
current_dragging_element.style.left = event.clientX - 20
current_dragging_element.style.top = event.clientY - 20
current_dragging_element.classList.add("drag");
current_dragging_element.style.position = "fixed";
current_dragging_element.style.zIndex = 999;
}
This is what I have far, however it doesn't function correctly yet. Any ideas?
Element.closest() works like a CSS selector, just like querySelector(). You can add multiple classes in a single string and get the first encounter of one of those elements.
See example below.
const entries = document.querySelectorAll('.entry');
entries.forEach(entry => {
const closest = entry.closest('.draggable_list, .draggable_item');
console.log(closest);
});
<!-- draggable item is the closest -->
<div class="draggable_list">
<div class="draggable_item">
<div class="entry"></div>
</div>
</div>
<!-- draggable list is the closest -->
<div class="draggable_list">
<div class="entry"></div>
</div>
EDIT: I cleaned up the code a bit and narrowed down the problem.
So I'm working on a Wordpress site, and I'm trying to incorporate drop-downs into my menu on mobile, which means I have to use jQuery to assign classes and id's to my already existing elements. I have this code that already works on premade HTML, but fails on dynamically created id's.
Here is the code:
...
var menuCount = 0;
var contentCount = 0;
//find the mobile menu items
var submenus = $('[title="submenu"]');
if (submenus.length && submenus.parent('.fusion-mobile-nav-item')) {
console.log(submenus);
submenus.addClass('dropdown-title').append('<i id="dropdown-angle" class="fa fa-angle-down" aria-hidden="true"></i>');
submenus.each(function() {
$(this).attr("href", "#m" + menuCount++);
})
var content = submenus.parent().find('ul.sub-menu');
content.addClass('dropdown-content');
content.each(function() {
$(this).attr("id", "m" + contentCount++);
})
}
$(document).on('click', '.dropdown-title', function(e) {
var currentAttrValue = $(this).attr('href');
if ($(e.target).is('.d-active') || $(e.target).parent('.dropdown-title').is('.d-active')) {
$(this).removeClass('d-active');
$(currentAttrValue).slideUp(300).removeClass('d-open');
} else {
$('.dropdown-title').removeClass('d-active');
$('.dropdown-content').slideUp(300).removeClass('d-open');
$(this).addClass('d-active');
console.log($(currentAttrValue));
//THIS LINE FAILS
$(currentAttrValue).slideDown(300).addClass('d-open');
}
e.preventDefault();
});
I've registered the elements with the class dropdown-title using $(document).on(...) but I can't figure out what I need to do to register the elements with the custom ID's. I've tried putting the event callback inside the .each functions, I've tried making custom events to trigger, but none of them will get the 2nd to last line of code to trigger. There's no errors in the console, and when I console log the selector I get this:
[ul#m0.sub-menu.dropdown-content, context: document, selector: "#m0"]
0
:
ul#m0.sub-menu.dropdown-content
context
:
document
length
:
1
selector
:
"#m0"
proto
:
Object[0]
So jQuery knows the element is there, I just can't figure out how to register it...or maybe it's something I'm not thinking of, I don't know.
If you are creating your elements dynamically, you should be assigning the .on 'click' after creating those elements. Just declare the 'on click' callback code you posted after adding the ids and classes instead of when the page loads, so it gets attached to the elements with .dropdown-title class.
Check this jsFiddle: https://jsfiddle.net/6zayouxc/
EDIT: Your edited JS code works... There also might be some problem with your HTML or CSS, are you hiding your submenus? Make sure you are not making them transparent.
You're trying to call a function for a attribute, instead of the element. You probably want $(this).slideDown(300).addClass('d-active'); (also then you don't need $(this).addClass('d-active'); before)
Inside submenus.each loop add your callback listener.
As you are adding the class dropdown-title dynamically, it was not available at dom loading time, that is why event listener was not attached with those elemnts.
var menuCount = 0;
var contentCount = 0;
//find the mobile menu items
var submenus = $('[title="submenu"]');
if (submenus.length && submenus.parent('.fusion-mobile-nav-item')) {
console.log(submenus);
submenus.addClass('dropdown-title').append('<i id="dropdown-angle" class="fa fa-angle-down" aria-hidden="true"></i>');
submenus.each(function() {
$(this).attr("href", "#m" + menuCount++);
// add callback here
$(this).click( function(e) {
var currentAttrValue = $(this).attr('href');
if ($(e.target).is('.d-active') || $(e.target).parent('.dropdown-title').is('.d-active')) {
$(this).removeClass('d-active');
$(currentAttrValue).slideUp(300).removeClass('d-open');
} else {
$('.dropdown-title').removeClass('d-active');
$('.dropdown-content').slideUp(300).removeClass('d-open');
$(this).addClass('d-active');
console.log($(currentAttrValue));
$(currentAttrValue).slideDown(300).addClass('d-active');
}
e.preventDefault();
});
})
var content = submenus.parent().find('ul.sub-menu');
content.addClass('dropdown-content');
content.each(function() {
$(this).attr("id", "m" + contentCount++);
})
}
Turns out my problem is that jQuery is adding to both the mobile menu and the desktop menu, where the desktop menu is being loaded first when I search for that ID that's the one that jQuery finds. So it turns out I was completely wrong about my suspicions.
I am using the drag and drop to be able to move one of my nodes within a page. What I want to be able to do is once the drag and drop is completed, get the XY position and if it is outside a certain position (XY), then the class applied to the node should be updated.
http://jsfiddle.net/gabrielesandoval/ab1cjrcj/
CSS:
.dd-demo-inside {
background-color: #8DD5E7;
color: #000;
}
.dd-demo-outside {
background-color: #004C6D;
}
JS:
YUI().use('dd-constrain', function(Y) {
var dd1 = new Y.DD.Drag({
node: '#dd-demo-1'
}).plug(Y.Plugin.DDConstrained, {
constrain2node: '#dd-demo-canvas1'
});
});
So in the JS fiddle example above, if the box moves to the outer color, then the CSS applied to "dd-demo-1" should change from .dd-demo-inside to .dd-demo-outside.
I know YUI has a getXY() function but I wasnt sure how the best way to use it or what event it can be used on to make sure it is called once the dragging of the node is completed.
Any help you can provide would be much appreciated.
You can use the Node.inRegion method to test if the node is inside another node, passing true as the second parameter will ensure that it is fully inside the target region.
http://jsfiddle.net/ab1cjrcj/16/
YUI().use('dd-constrain', function(Y) {
var dragNode = Y.one('#dd-demo-1'),
innerCanvasNode = Y.one('#dd-demo-canvas3'),
dd1;
dd1 = new Y.DD.Drag({
node: dragNode
}).plug(Y.Plugin.DDConstrained, {
constrain2node: '#dd-demo-canvas1'
});
dd1.on('drag:end', function(e){
if (dragNode.inRegion(innerCanvasNode, true)){
dragNode.replaceClass('dd-demo-outside', 'dd-demo-inside');
} else {
dragNode.replaceClass('dd-demo-inside', 'dd-demo-outside');
}
//console.log(dragNode.inRegion(innerCanvasNode, true));
});
});
So i updated my own code. I subscirbed to the drag:end event--
dd1.on('drag:end', getOffsetTop);
Then I make a pure JS function that just checks for the offsetTop and offsetLeft. I think I should be able to create my own condition based on these values to change the class names.
Once you release you can call a function that uses javascript to retrieve the X and Y offset and update the class accordingly. Assuming you're using jQuery it could look something like this.
var offset = $(element).offset();
if(offset.left > x && offset.top > y) {
element.addClass(newClass);
}
I built onto your JSFiddle to show how it would work http://jsfiddle.net/ab1cjrcj/12/
Note: Changed code so that images and texts are links.
Basically, I have 3 pictures all with the same class, different ID. I have a javascript code which I want to apply to all three pictures, except, the code needs to be SLIGHTLY different depending on the picture. Here is the html:
<div class=column1of4>
<img src="images/actual.jpg" id="first">
<div id="firsttext" class="spanlink"><p>lots of text</p></div>
</div>
<div class=column1of4>
<img src="images/fake.jpg" id="second">
<div id="moretext" class="spanlink"><p>more text</p></div>
</div>
<div class=column1of4>
<img src="images/real.jpg" id="eighth">
<div id="evenmoretext" class="spanlink"><p>even more text</p></div>
</div>
Here is the Javascript for the id="firsttext":
$('#firstextt').hide();
$('#first, #firsttext').hover(function(){
//in
$('#firsttext').show();
},function(){
//out
$('#firsttext').hide();
});
So when a user hovers over #first, #firsttext will appear. Then, I want it so that when a user hovers over #second, #moretext should appear, etc.
I've done programming in Python, I created a sudo code and basically it is this.
text = [#firsttext, #moretext, #evenmoretext]
picture = [#first, #second, #eighth]
for number in range.len(text) //over here, basically find out how many elements are in text
$('text[number]').hide();
$('text[number], picture[number]').hover(function(){
//in
$('text[number]').show();
},function(){
//out
$('text[number]').hide();
});
The syntax is probably way off, but that's just the sudo code. Can anyone help me make the actual Javascript code for it?
try this
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink").show();
});
Why not
$('.spanlink').hide();
$('.column1of4').hover(
function() {
// in
$(this).children('.spanlink').show();
},
function() {
// out
$(this).children('.spanlink').hide();
}
);
It doesn't even need the ids.
You can do it :
$('.column1of4').click(function(){
$(this); // the current object
$(this).children('img'); // img in the current object
});
or a loop :
$('.column1of4').each(function(){
...
});
Dont use Id as $('#id') for multiple events, use a .class or an [attribute] do this.
If you're using jQuery, this is quite easy to accomplish:
$('.column1of4 .spanlink').hide();
$('.column1of4 img').mouseenter(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').show();
});
$('.column1of4 img').mouseleave(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').hide();
});
Depending on your markup structure, you could use DOM traversing functions like .filter(), .find(), .next() to get to your selected node.
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink, img").show();
});
So, the way you would do this, given your html would look like:
$('.column1of4').on('mouseenter mouseleave', 'img, .spanlink', function(ev) {
$(ev.delegateTarget).find('.spanlink').toggle(ev.type === 'mouseenter');
}).find('.spanlink').hide();
But building on what you have:
var text = ['#firsttext', '#moretext', '#evenmoretext'];
var picture = ['#first', '#second', '#third'];
This is a traditional loop using a closure (it's better to define the function outside of the loop, but I'm going to leave it there for this):
// You could also do var length = text.length and replace the "3"
for ( var i = 0; i < 3; ++i ) {
// create a closure so that i isn't incremented when the event happens.
(function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(',')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
})(i);
}
And the following is using $.each to iterate over the group.
$.each(text, function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(', ')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
});
Here's a fiddle with all three versions. Just uncomment the one you want to test and give it a go.
I moved the image inside the div and used this code, a working example:
$('.column1of4').each(function(){
$('div', $(this)).each(function(){
$(this).hover(
function(){
//in
$('img', $(this)).show();
},
function(){
//out
$('img', $(this)).hide();
});
});
});
The general idea is 1) use a selector that isn't an ID so I can iterate over several elements without worrying if future elements will be added later 2) locate the div to hide/show based on location relational to $(this) (will only work if you repeat this structure in your markup) 3) move the image tag inside the div (if you don't, then the hover gets a little spazzy because the positioned is changed when the image is shown, therefore affecting whether the cursor is inside the div or not.
EDIT
Updated fiddle for additional requirements (see comments).
I am looking for an example of drag and drop where the drag item has two distinct areas that have to match up with two droppable areas.
Example:
I would like the blue drag item to revert unless it is dropped in a position where each of its red children land on a green area.
Ideally I would like to use jquery ui (as I have experience with it), but any javascript library would be fine, thanks in advance.
You can accomplish this by using a combination of draggable/droppable options. Given HTML like this:
<div id="blue" class="valid">
<div id="red-one" class="red"></div>
<div id="red-two" class="red"></div>
</div>
<div id="green-container">
<div id="green-one" class="green">
</div>
<div id="green-two" class="green">
</div>
</div>
(omitting CSS, I did add some rules, see in the fiddle below).
You can write JavaScript like this:
function isInside(one, other) {
return one.offset().left >= other.offset().left &&
one.offset().top >= other.offset().top &&
one.offset().top + one.height() <= other.offset().top + other.height() &&
one.offset().left + one.width() <= other.offset().left + other.width();
}
$("#blue").draggable({
drag: function(event, ui) {
var $this = $(this);
var $reds = $this.children(".red");
var $greens = $("#green-container").children(".green");
var firstRed = $reds.first();
var firstGreen = $greens.first();
var secondRed = $reds.last();
var secondGreen = $greens.last();
if (isInside(firstRed, firstGreen) && isInside(secondRed, secondGreen)) {
$this.addClass('valid');
}
else {
$this.removeClass('valid');
}
},
revert: 'invalid'
});
$("#green-container").droppable({ accept: ".valid" });
Check it out here: http://jsfiddle.net/andrewwhitaker/g6FKz/
Notes:
For some reason I had to apply the 'valid' class initially to the 'blue' div, or else the target droppable would not accept the dragged element, even if it was valid (would appreciate some input on this). Not sure what's up with that, might be a bug in jQueryUI. Not a huge deal though.
The target droppable isn't exactly the two green elements, it's a white div that contains those elements. This should be clear from the example.
Every time you move the draggable div, the "drag" event is called, which determines if the red boxes are inside the green ones and assigns a valid class to the draggable div. The droppable object only accepts valid draggables.
Hope that helps!