In my project I'm using this drag and drop library called gridstack. You can see their documentation on github here. When you hardcode elements inside the dom and initialize the gridstack, those elements are draggable. But when the elements are created dynamically with a forloop, they are not draggable even if they have the proper draggable classes. How can I make this work?
//initialize grid stack
var grid = GridStack.init({
minRow: 5, // don't collapse when empty
cellHeight: 70,
acceptWidgets: true,// acceptWidgets - accept widgets dragged from other grids or from outside (default: false).
dragIn: '.newWidget', // class that can be dragged from outside
dragInOptions: { revert: 'invalid', scroll: false, appendTo: 'body', helper:'clone' }, // clone or can be your function
removable: '#trash', // drag-out delete class
});
//gridstack on change
grid.on('added removed change', function(e, items) {
let str = '';
items.forEach(function(item) { str += ' (x,y)=' + item.x + ',' + item.y; });
console.log(e.type + ' ' + items.length + ' items:' + str );
});
//dynamic elemenets
const arr = ["Bruh cant drag me!", "Nope me neither", "Me too mouhahaha"];
//loop
for (let i = 0; i < arr.length; i++) {
var div = document.createElement('div');
var el = "<div class='newWidget grid-stack-item ui-draggable ui-resizable ui-resizable-autohide'> <div class='grid-stack-item-content' style='padding: 5px;'> "+arr[i]+"</div></div>";
div.innerHTML = el;
$('.dynamic').append(div);
}
.grid-stack-item-removing {
opacity: 0.8;
filter: blur(5px);
}
#trash {
background: rgba(255, 0, 0, 0.4);
padding: 5px;
text-align: center;
}
.grid-stack-item{
background: whitesmoke;
width: 50%;
border: 1px dashed grey;
}
.grid-stack {
background : #F0FFC0;
}
<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!-- gridstack-->
<link rel="stylesheet" href="https://gridstackjs.com/node_modules/gridstack/dist/gridstack-extra.min.css"/>
<script src="https://gridstackjs.com/node_modules/gridstack/dist/gridstack-h5.js"></script>
<!-- body-->
<body>
<div id="trash"><span>drop here to remove</span> </div>
<br>
<div class="dynamic"></div>
<div class="newWidget grid-stack-item ui-draggable ui-resizable ui-resizable-autohide">
<div class="grid-stack-item-content" style="padding: 5px;">
<div>
</div>
<div>
<span>I'm original domster! Drag and drop me!</span>
</div>
</div>
</div>
<br>
<div class="grid-stack"></div>
</body>
This issue was raised here. The grid does not automatically track external changes so the grid needs to be re-initialize for the dragIn option to notice the new dynamic widgets
GridStack.setupDragIn()
Full code
//initialize grid stack
var grid = GridStack.init({
minRow: 5, // don't collapse when empty
cellHeight: 70,
acceptWidgets: true,// acceptWidgets - accept widgets dragged from other grids or from outside (default: false).
dragIn: '.newWidget', // class that can be dragged from outside
dragInOptions: { revert: 'invalid', scroll: false, appendTo: 'body', helper:'clone' }, // clone or can be your function
removable: '#trash', // drag-out delete class
});
//gridstack on change
grid.on('added removed change', function(e, items) {
let str = '';
items.forEach(function(item) { str += ' (x,y)=' + item.x + ',' + item.y; });
console.log(e.type + ' ' + items.length + ' items:' + str );
});
//dynamic elemenets
const arr = ["Bruh cant drag me!", "Nope me neither", "Me too mouhahaha"];
//loop
for (let i = 0; i < arr.length; i++) {
var div = document.createElement('div');
var el = "<div class='newWidget grid-stack-item ui-draggable ui-resizable ui-resizable-autohide'> <div class='grid-stack-item-content' style='padding: 5px;'> "+arr[i]+"</div></div>";
div.innerHTML = el;
$('.dynamic').append(div);
}
GridStack.setupDragIn(
'.newWidget',
);
.grid-stack-item-removing {
opacity: 0.8;
filter: blur(5px);
}
#trash {
background: rgba(255, 0, 0, 0.4);
padding: 5px;
text-align: center;
}
.grid-stack-item{
background: whitesmoke;
width: 50%;
border: 1px dashed grey;
}
.grid-stack {
background : #F0FFC0;
}
<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!-- gridstack-->
<link rel="stylesheet" href="https://gridstackjs.com/node_modules/gridstack/dist/gridstack-extra.min.css"/>
<script src="https://gridstackjs.com/node_modules/gridstack/dist/gridstack-h5.js"></script>
<!-- body-->
<body>
<div id="trash"><span>drop here to remove</span> </div>
<br>
<div class="dynamic"></div>
<div class="newWidget grid-stack-item ui-draggable ui-resizable ui-resizable-autohide">
<div class="grid-stack-item-content" style="padding: 5px;">
<div>
</div>
<div>
<span>I'm original domster! Drag and drop me!</span>
</div>
</div>
</div>
<br>
<div class="grid-stack"></div>
</body>
Related
Html/css newbie here,
I am using interact.js to attain a certain UI where I can drop items from a list into a drop zone. The problem is my list can grow very long and I need to add scroll to the list, and when I try to do so I have create a 'div' and put the list items into it to show the scroll behaviour.
But when I put the list items inside a div and the drop zone outside it, the items do not get dropped there and the list shows a weird behaviour, all of them starts getting stacked on top of the bottom list item (at the bottom of the div containing the items).
This is my html:
<div class="items">
<p style="padding-top: 20px; font-size:18px">Stacked Items</p>
<div style = "height: 400px; overflow: scroll">
<div id="itemstodrop" class="drag-drop"> item 1 </div>
<div id="itemstodrop" class="drag-drop"> item 2 </div>
<div id="itemstodrop" class="drag-drop"> item 3 </div>
<div id="itemstodrop" class="drag-drop"> item 4 </div>
<div id="itemstodrop" class="drag-drop"> item 5 </div>
<div id="itemstodrop" class="drag-drop"> item 6 </div>
<div id="itemstodrop" class="drag-drop"> item 7 </div>
<div id="itemstodrop" class="drag-drop"> item 8 </div>
<div id="itemstodrop" class="drag-drop"> item 9 </div>
<div id="itemstodrop" class="drag-drop"> item 10 </div>
<div id="itemstodrop" class="drag-drop"> item 11 </div>
<div id="itemstodrop" class="drag-drop"> item 12 </div>
</div>
<div id="inner-dropzone" class="dropzone">Drop here</div>
</div>
This is my script which holds interact.js code:
import interact from
'https://cdn.jsdelivr.net/npm/#interactjs/interactjs/index.js'
// enable draggables to be dropped into this
var startPos = null;
//define the initial position for each rig tile.
function dragMoveListener (event) {
var target = event.target
// keep the dragged position in the data-x/data-y attributes
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)'
// update the posiion attributes
target.setAttribute('data-x', x)
target.setAttribute('data-y', y)
}
// this function is used later in the resizing and gesture demos
window.dragMoveListener = dragMoveListener
//ALL THE FUNCTIONS BELOW TALK ABOUT THE DRAGGABLE AREA.
interact('.dropzone').dropzone({
// only accept elements matching this CSS selector
accept: '#itemstodrop',
// the item should go 100% inside the draggable area...
overlap: 0.9999999, //somehow it does not take the value 100%
// listen for drop related events:
ondropactivate: function (event) {
// add active dropzone feedback
event.target.classList.add('drop-active')
},
ondragenter: function (event) {
//when item enters the draggable area
var draggableElement = event.relatedTarget
var dropzoneElement = event.target
console.log(draggableElement.firstChild.nodeValue);
// feedback the possibility of a drop
dropzoneElement.classList.add('drop-target')
draggableElement.classList.add('can-drop')
},
ondragleave: function (event) {
console.log(startPos)
event.draggable.draggable({
snap: {
targets: [startPos]
}
});
//when item leaves the draggable area
// remove the drop feedback style
event.target.classList.remove('drop-target')
event.relatedTarget.classList.remove('can-drop')
},
ondrop: function (event) {
//when the item is droppd in the draggable area
{% comment %} event.relatedTarget.textContent = 'Dropped' {% endcomment %}
},
ondropdeactivate: function (event) {
// remove active dropzone feedback
event.target.classList.remove('drop-active')
event.target.classList.remove('drop-target')
}
})
interact('.drag-drop')
.draggable({
inertia: true,
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
autoScroll: true,
// dragMoveListener from the dragging demo above
listeners: { move: dragMoveListener }
})
</script>
This is how it looks when rendered: (Basically can't drop any item to drop area.)
Full working page for demo:
(I have added a comment which tells where have I put the div.)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#outer-dropzone {
height: 140px;
}
#inner-dropzone {
height: 80px;
}
.dropzone {
background-color: #ccc;
border: dashed 4px transparent;
border-radius: 4px;
margin: 10px auto 30px;
padding: 10px;
width: 80%;
transition: background-color 0.3s;
}
.drop-active {
border-color: #aaa;
}
.drop-target {
background-color: #29e;
border-color: #fff;
border-style: solid;
}
.drag-drop {
display: inline-block;
min-width: 40px;
padding: 2em 0.5em;
color: #fff;
background-color: #29e;
border: solid 2px #fff;
touch-action: none;
-webkit-transform: translate(0px, 0px);
transform: translate(0px, 0px);
transition: background-color 0.3s;
}
.drag-drop.can-drop {
color: #000;
background-color: #4e4;
}
</style>
</head>
<body>
{% comment %} I NEED THIS DIV UNDER THIS COMMENT, TO ADD A SCROLL AREA. BUT WHEN I GIVE THIS DIV, THE DROP DOES NOT OCCUR. {% endcomment %}
<div>
<div id="no-drop" class="drag-drop"> #no-drop </div>
<div id="yes-drop" class="drag-drop"> #yes-drop </div>
</div>
<div id="outer-dropzone" class="dropzone">
#outer-dropzone
<div id="inner-dropzone" class="dropzone">#inner-dropzone</div>
</div>
<script type="module">
import interact from
'https://cdn.jsdelivr.net/npm/#interactjs/interactjs/index.js'
// enable draggables to be dropped into this
interact('.draggable')
.draggable({
// enable inertial throwing
inertia: true,
// keep the element within the area of it's parent
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
// enable autoScroll
autoScroll: true,
listeners: {
// call this function on every dragmove event
move: dragMoveListener,
// call this function on every dragend event
end (event) {
var textEl = event.target.querySelector('p')
textEl && (textEl.textContent =
'moved a distance of ' +
(Math.sqrt(Math.pow(event.pageX - event.x0, 2) +
Math.pow(event.pageY - event.y0, 2) | 0))
.toFixed(2) + 'px')
}
}
})
function dragMoveListener (event) {
var target = event.target
// keep the dragged position in the data-x/data-y attributes
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)'
// update the posiion attributes
target.setAttribute('data-x', x)
target.setAttribute('data-y', y)
}
// this function is used later in the resizing and gesture demos
window.dragMoveListener = dragMoveListener
//ALL THE FUNCTIONS BELOW TALK ABOUT THE DRAGGABLE AREA.
interact('.dropzone').dropzone({
// only accept elements matching this CSS selector
accept: '#yes-drop',
// the item should go 100% inside the draggable area...
overlap: 0.9999999, //somehow it does not take the value 100%
// listen for drop related events:
ondropactivate: function (event) {
// add active dropzone feedback
event.target.classList.add('drop-active')
},
ondragenter: function (event) {
//when item enters the draggable area
var draggableElement = event.relatedTarget
var dropzoneElement = event.target
console.log(draggableElement.firstChild.nodeValue);
// feedback the possibility of a drop
dropzoneElement.classList.add('drop-target')
draggableElement.classList.add('can-drop')
},
ondragleave: function (event) {
//when item leaves the draggable area
// remove the drop feedback style
event.target.classList.remove('drop-target')
event.relatedTarget.classList.remove('can-drop')
},
ondrop: function (event) {
//when the item is droppd in the draggable area
{% comment %} event.relatedTarget.textContent = 'Dropped' {% endcomment %}
},
ondropdeactivate: function (event) {
// remove active dropzone feedback
event.target.classList.remove('drop-active')
event.target.classList.remove('drop-target')
}
})
interact('.drag-drop')
.draggable({
inertia: true,
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
autoScroll: true,
// dragMoveListener from the dragging demo above
listeners: { move: dragMoveListener }
})
</script>
</body>
</html>
You need to change accept: '#rigstodrop' to accept: '#itemstodrop' because here your div has id itemstodrop which you need to drag and drop . Also , use restriction: '.items' to restrict rect not to go beyond that area .
Demo code :
var startPos = null;
//define the initial position for each rig tile.
function dragMoveListener(event) {
var target = event.target
// keep the dragged position in the data-x/data-y attributes
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)'
// update the posiion attributes
target.setAttribute('data-x', x)
target.setAttribute('data-y', y)
}
// this function is used later in the resizing and gesture demos
window.dragMoveListener = dragMoveListener
interact('.dropzone').dropzone({
// only accept elements matching this CSS selector
accept: '#itemstodrop', //change this
// the item should go 100% inside the draggable area...
overlap: 0.9999999,
ondropactivate: function(event) {
// add active dropzone feedback
event.target.classList.add('drop-active')
},
ondragenter: function(event) {
//when item enters the draggable area
var draggableElement = event.relatedTarget
var dropzoneElement = event.target
console.log(draggableElement.firstChild.nodeValue);
// feedback the possibility of a drop
dropzoneElement.classList.add('drop-target')
draggableElement.classList.add('can-drop')
},
ondragleave: function(event) {
console.log(startPos)
event.draggable.draggable({
snap: {
targets: [startPos]
}
});
//when item leaves the draggable area
// remove the drop feedback style
event.target.classList.remove('drop-target')
event.relatedTarget.classList.remove('can-drop')
},
ondrop: function(event) {
//when the item is droppd in the draggable area
event.relatedTarget.textContent = 'Dropped'
},
ondropdeactivate: function(event) {
// remove active dropzone feedback
event.target.classList.remove('drop-active')
event.target.classList.remove('drop-target')
}
})
interact('.drag-drop')
.draggable({
inertia: true,
modifiers: [
interact.modifiers.restrictRect({
restriction: '.items', //change this
endOnly: true
})
],
autoScroll: true,
// dragMoveListener from the dragging demo above
listeners: {
move: dragMoveListener
}
})
.itemstodrop {
touch-action: none;
user-select: none;
}
#inner-dropzone {
height: 80px;
}
.dropzone {
background-color: #ccc;
border: dashed 4px transparent;
border-radius: 4px;
margin: 10px auto 30px;
padding: 10px;
width: 80%;
transition: background-color 0.3s;
}
.drop-active {
border-color: #aaa;
}
.drop-target {
background-color: #29e;
border-color: #fff;
border-style: solid;
}
.drag-drop {
display: inline-block;
min-width: 40px;
padding: 2em 0.5em;
color: #fff;
background-color: #29e;
border: solid 2px #fff;
touch-action: none;
-webkit-transform: translate(0px, 0px);
transform: translate(0px, 0px);
transition: background-color 0.3s;
}
.drag-drop.can-drop {
color: #000;
background-color: #4e4;
}
<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>
<div class="items">
<p style="padding-top: 20px; font-size:18px">Stacked Rigs</p>
<div style="height: auto;overflow: scroll">
<div id="itemstodrop" class="drag-drop itemstodrop"> item 1 </div>
<div id="itemstodrop" class="drag-drop itemstodrop"> item 2 </div>
<div id="itemstodrop" class="drag-drop itemstodrop"> item 3 </div>
<div id="itemstodrop" class="drag-drop itemstodrop"> item 4 </div>
<div id="itemstodrop" class="drag-drop itemstodrop"> item 5 </div>
<div id="itemstodrop" class="drag-drop itemstodrop"> item 6 </div>
<div id="itemstodrop" class="drag-drop itemstodrop"> item 7 </div>
<div id="itemstodrop" class="drag-drop itemstodrop"> item 8 </div>
<div id="itemstodrop" class="drag-drop itemstodrop"> item 9 </div>
<div id="itemstodrop" class="drag-drop itemstodrop"> item 10 </div>
<div id="itemstodrop" class="drag-drop itemstodrop"> item 11 </div>
<div id="itemstodrop" class="drag-drop itemstodrop"> item 12 </div>
<!--put this inside div-->
<div id="inner-dropzone" class="dropzone">Drop here</div>
</div>
</div>
I'm trying to setup multiple-step form in which the first step is visible by default and rest of the steps are hidden with class "hide". I'd like to switch the class with Next and Back button so only one step is visible at a time. Could you please help with this (Already spent an hour on this)
<div class="steps">
<div class="step1">step1</div>
<div class="step2 hide">step2</div>
<div class="step3 hide">step3</div>
<div class="step4 hide">step4</div>
</div>
<div class="back">Back</div>
<div class="next">Next</div>
$('.next').click(function(){
$('div:not(.hide)').next().removeClass('hide');
$('.hide').prev().removeClass('hide')
})
Try combining the 2 actions into one, like so:
$('.next').click(function(){
$('.steps div:not(.hide)').addClass('hide').next().removeClass('hide');
})
That way, you add the .hide class on your current div and then remove it on the next one.
You can use something similar for the Back button, by replacing .next() with .previous()
$('.next').click(function() {
// find the div that is not hidden
var $current = $('.steps div:not(.hide)');
// only perform logic if there is a proceeding div
if ($current.next().length) {
// show the next div
$current.next().removeClass('hide');
// hide the old current div
$current.addClass('hide')
}
});
$('.back').click(function() {
// find the div that is not hidden
var $current = $('.steps div:not(.hide)');
// only perform logic if there is a preceeding div
if ($current.prev().length) {
// show the previous div
$current.prev().removeClass('hide');
// hide the old current div
$current.addClass('hide')
}
});
.hide { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="steps">
<div class="step1">step1</div>
<div class="step2 hide">step2</div>
<div class="step3 hide">step3</div>
<div class="step4 hide">step4</div>
</div>
<div class="back">Back</div>
<div class="next">Next</div>
You can add a current step variable to track the currently displayed step and two css for styling and showing your content.
jQuery(function($) {
let currentstep = 1;
let maxsteps = 4;
function showstep(step) {
let step_c = '.step' + step;
for (i = 1; i <= maxsteps; i++) {
var step_selector = '.step' + i;
$(step_selector).removeClass('show');
$(step_selector).addClass('hide');
}
$(step_c).removeClass('hide');
$(step_c).addClass('show');
};
$('.next').click(function() {
currentstep = currentstep + 1;
currentstep = (currentstep % (maxsteps + 1));
if (currentstep == 0) currentstep = 1;
showstep(currentstep);
});
$('.back').click(function() {
currentstep = currentstep - 1;
currentstep = (currentstep % (maxsteps + 1));
if (currentstep == 0) currentstep = 4;
showstep(currentstep);
});
});
.hide {
display: none;
}
.show {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="steps">
<div class="step1 show">step1</div>
<div class="step2 hide">step2</div>
<div class="step3 hide">step3</div>
<div class="step4 hide">step4</div>
</div>
<div class="back">Back</div>
<div class="next">Next</div>
I converted Taplar's answer to a jQuery plugin.
You are essentially navigating left or right by one, using the previous and next functions. These functions navigate through the sibling elements.
(function() {
$.fn.moveRight = function(className) {
var $curr = this.find('div:not(.' + className + ')');
if ($curr.next().length) $curr.next().removeClass(className);
else this.find('div:first-child').removeClass(className);
$curr.addClass(className);
return this;
};
$.fn.moveLeft = function(className) {
var $curr = this.find('div:not(.' + className + ')');
if ($curr.prev().length) $curr.prev().removeClass(className);
else this.find('div:last-child').removeClass(className);
$curr.addClass(className);
return this;
};
})(jQuery);
$('.next').on('click', (e) => $('.steps').moveRight('hide'));
$('.back').on('click', (e) => $('.steps').moveLeft('hide'));
.hide {
display: none;
}
.nav {
width: 260px;
text-align: center;
}
.nav .nav-btn::selection { background: transparent; }
.nav .nav-btn::-moz-selection { background: transparent; }
.nav .nav-btn {
display: inline-block;
cursor: pointer;
}
.steps {
width: 260px;
height: 165px;
border: thin solid black;
text-align: center;
line-height: 165px;
font-size: 3em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="steps">
<div class="step1">step1</div>
<div class="step2 hide">step2</div>
<div class="step3 hide">step3</div>
<div class="step4 hide">step4</div>
</div>
<div class="nav">
<div class="nav-btn back">[ << Back ]</div>
<div class="nav-btn next">[ Next >> ]</div>
</div>
Report designer detail band contains Add band button which shoud add new panels immediately before and after detail panel.
$parentpanel = $this.parents(".designer-panel:first");
is used to find parent panel and .prepend() / append() to add new panels.
Panels are added as Detail panel child elements.
How to add panels before and after Detail panel in same DOM level like group header and footer panels in sample html.
Elements should probably added to $parentpanel.parent() element list before and after $parentpanel element.
Is there some selector or append command in jQuery for this ?
$(function() {
var startpos,
selected = $([]),
offset = {
top: 0,
left: 0
};
$('#designer-detail-addband').on('click', function() {
var $this = $(this),
$parentpanel = $this.parents(".designer-panel:first");
$parentpanel.prepend('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px">' +
'</div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group heade {0}: <span id="band{0}_expr" contenteditable="true">"groupexpression"</span>' +
'</div></div></div>');
$parentpanel.append('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px"></div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group footer {0}' +
'</div></div></div>');
});
$(".designer-panel-body").droppable({
accept: ".designer-field"
});
$(".designer-field").draggable({
start: function(event, ui) {
var $this = $(this);
if ($this.hasClass("ui-selected")) {
selected = $(".ui-selected").each(function() {
var el = $(this);
el.data("offset", el.offset());
});
} else {
selected = $([]);
$(".designer-field").removeClass("ui-selected");
}
offset = $this.offset();
},
drag: function(event, ui) {
// drag all selected elements simultaneously
var dt = ui.position.top - offset.top,
dl = ui.position.left - offset.left;
selected.not(this).each(function() {
var $this = $(this);
var elOffset = $this.data("offset");
$this.css({
top: elOffset.top + dt,
left: elOffset.left + dl
});
});
}
});
$(".panel-resizable").resizable({
minWidth: "100%",
maxWidth: "100%",
minHeight: 1
});
})
.panel-resizable {
min-height: 1px;
overflow: hidden;
margin: 0;
padding: 0;
}
.designer-field {
border: 1px solid lightgray;
white-space: pre;
overflow: hidden;
position: absolute;
}
.designer-panel-body {
min-height: 1px;
overflow: hidden;
margin: 0;
padding: 0;
}
.panel-footer {
padding: 0;
}
.designer-panel,
.panel-body {
margin: 0;
padding: 0;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<div class='panel designer-panel'>
<div class='panel-body designer-panel-body panel-resizable' style='height:2cm'>
<div class='designer-field' style='left:5px;top:6px;width:180px'>field 1 in group 1 header</div>
<div class='designer-field' style='left:54px;top :36px;width:160px'>field 2 in group 1 header</div>
</div>
<div class='panel-footer'>Group 1 Header</div>
</div>
<div class='panel designer-panel'>
<div class='panel-body panel-resizable' style='height:1cm'>
<div class='designer-field' style='left:24px;top:2px;width:140px'>field in detail group</div>
</div>
<div class='panel-footer panel-primary'>Detail <a role="button" id="designer-detail-addband"> Add group</a>
</div>
</div>
<div class='panel'>
<div class='panel-body panel-resizable' style='height:1cm'>
<div class='designer-field' style='left:44px;top:2px;width:140px'>field in group 1 footer</div>
</div>
<div class='panel-footer panel-warning'>Group 1 Footer</div>
</div>
Try jQuery's before, after functions. Or insertBefore, insertAfter
Also you can use
$this.closest(".designer-panel");
instead of
$this.parents(".designer-panel:first");
See closest
Report designer layout contains Bootstrap 3 panels.
Detail panel has Add group button which should add new panels before and after it.
This is implemented in onclick event handler using jquery prepend and append:
var $this = $(this),
$parentpanel = $this.parents(".designer-panel").get(0);
$parentpanel.prepend('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px">' +
'</div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group heade {0}: <span id="band{0}_expr" contenteditable="true">"group expression"</span>' +
'</div></div></div>');
$parentpanel.append('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px">' +
'</div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group footer {0}' +
'</div></div></div>');
});
If clicked in Add band button html appears instead of panel.
It looks like jquery preoend and append does not add dom objects work for unknown reason.
How to fix this so that new panels appear before and after detail panel ?
$(function() {
var startpos,
selected = $([]),
offset = { top: 0, left: 0 };
$('#designer-detail-addband').on('click', function () {
var $this = $(this),
$parentpanel = $this.parents(".designer-panel").get(0);
$parentpanel.prepend('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px">' +
'</div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group heade {0}: <span id="band{0}_expr" contenteditable="true">"groupexpression"</span>' +
'</div></div></div>');
$parentpanel.append('<div class="panel designer-panel">' +
'<div class="panel-body designer-panel-body" style="height:1px"></div>' +
'<div class="bg-warning">' +
'<div class="panel-footer"><i class="glyphicon glyphicon-chevron-up">' +
'</i> Group footer {0}' +
'</div></div></div>');
});
$(".designer-panel-body").droppable({
accept: ".designer-field"
});
$(".designer-field").draggable({
start: function (event, ui) {
var $this = $(this);
if ($this.hasClass("ui-selected")) {
selected = $(".ui-selected").each(function () {
var el = $(this);
el.data("offset", el.offset());
});
} else {
selected = $([]);
$(".designer-field").removeClass("ui-selected");
}
offset = $this.offset();
},
drag: function (event, ui) {
// drag all selected elements simultaneously
var dt = ui.position.top - offset.top, dl = ui.position.left - offset.left;
selected.not(this).each(function () {
var $this = $(this);
var elOffset = $this.data("offset");
$this.css({ top: elOffset.top + dt, left: elOffset.left + dl });
});
}
});
$(".panel-resizable").resizable({
minWidth: "100%",
maxWidth: "100%",
minHeight: 1
});
});
.panel-resizable {
min-height: 1px;
overflow: hidden;
margin: 0;
padding: 0;
}
.designer-field {
border: 1px solid lightgray;
white-space: pre;
overflow: hidden;
position: absolute;
}
.designer-panel-body {
min-height: 1px;
overflow: hidden;
margin: 0;
padding: 0;
}
.panel-footer {
padding: 0;
}
.designer-panel, .panel-body {
margin: 0;
padding: 0;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<div class='panel designer-panel'>
<div class='panel-body designer-panel-body panel-resizable' style='height:2cm'>
<div class='designer-field' style='left:5px;top:6px;width:180px'>field 1 in group 1 header</div>
<div class='designer-field' style='left:54px;top :36px;width:160px'>field 2 in group 1 header</div>
</div>
<div class='panel-footer'>Group 1 Header</div>
</div>
<div class='panel designer-panel'>
<div class='panel-body panel-resizable' style='height:1cm'>
<div class='designer-field' style='left:24px;top:2px;width:140px'>field in detail group </div>
</div>
<div class='panel-footer panel-primary'>Detail <a role="button" id="designer-detail-addband"> Add group</a></div>
</div>
<div class='panel'>
<div class='panel-body panel-resizable' style='height:1cm'>
<div class='designer-field' style='left:44px;top:2px;width:140px'>field in group 1 footer</div></div>
<div class='panel-footer panel-warning'>Group 1 Footer</div>
</div>
I think your issue is here:
$parentpanel = $this.parent(".designer-panel");
jQuery parent only goes one level up the DOM, and looking at your HTML the first div with .designer-panel is several levels up from your anchor. If you change it to the code below then you should hopefully get the element you want.
$parentpanel = $this.parents(".designer-panel").get(0);
So after trying different things for 3 hours or so, I finally decided to post a question on StackOverFlow. Here is the problem:
On click of the "next" button, I want to remove the old div by sliding it to the left and add a dynamically created div by sliding it from the right.
So far, I can only create the remove effect by sliding it to the left while fading it. But I can't add a new div sliding in from the right. How would I accomplish this?
Here is the html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Website Google Project</title>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="bootstrap-2.3.6-dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>
<script type="text/javascript" src="js/secret_api.js"></script>
<link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/styles.css">
<link rel="shortcut icon" type="image/ico" href="photos/favIcon.png">
</head>
<body>
<h1 class="text-center">All Your Directions In One Spot</h1>
<div class="container">
<div class="row row-content" id="tempDiv">
<div class="col-xs-12 col-sm-6 col-sm-offset-3">
<div class="text-center">
<h2>From:</h2>
</div>
</div>
<div style="padding: 20px 20px"></div>
<div class="col-xs-12 col-sm-6 col-sm-offset-3">
<div>
<input id="origin" type="text" class="form-control input-lg" placeholder="Origin" value="8844 N Wisner St">
</div>
</div>
<div style="padding: 40px 40px"></div>
<div class="col-xs-12 col-sm-6 col-sm-offset-3">
<div class="row row-content">
<div class="text-center">
<div class="col-xs-12 col-sm-3 col-sm-offset-3">
<button class ="btn btn-lg" id="next">Next</button>
</div>
<div class="col-xs-12 col-sm-3">
<button class="btn btn-lg" id="done">Done</button>
</div>
</div>
</div>
</div>
</div>
<div style="padding: 40px 40px"></div>
<div id="listDirections">
</div>
</div>
<script src="js/scripts.js"></script>
</body>
</html>
Here is the Css:
body {
background-color: #2b669a;
}
h1 {
color: white;
font-size: 3em;
}
button {
background-color: #204056;
color: white;
font-weight: bold;
}
button:hover,
button:focus {
color: lightgray !important;
}
.directions {
background-color: whitesmoke;
color: #5A5A5A;
padding: 20px 20px;
font-size: 1.5em;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
margin-bottom: 20px;
}
.glyphicon-plus {
font-size: 2em;
color: white;
padding: 5px 5px;
}
.glyphicon-plus:hover {
color: coral;
cursor: pointer;
}
Here is the javascript:
function getDirections(json) {
"use strict";
var steps = json.routes[0].legs[0].steps;
var directions = [];
var counter = 1;
steps.forEach(function (step) {
directions.push(counter + ". " + step.html_instructions);
counter += 1;
});
// Separates the 2 conjoint words in the last line.
// so "Ave Destination" instead of "AveDestination"
directions[directions.length - 1] = directions[directions.length - 1].replace(/([a-z])([A-Z])/g, "$1 $2");
return directions;
}
/**
* Takes in the Google Maps API JSON object as input and returns the ETA as a string.
* #param {Object} json
* #return {string}
*/
function getEta(json) {
"use strict";
return json.routes[0].legs[0].duration.text;
}
function showDirections(json) {
"use strict";
// creates div, adds class, and appends the div
var div = document.createElement("div");
$(div).addClass("directions col-xs-12 col-sm-8 col-sm-offset-2");
$(div).append("<b>FROM: </b> " + $("#origin").val() + "<br>");
$(div).append("<b>TO: </b>" + $("#destination").val() + "<br>");
$(div).append("<em>It will take you " + getEta(json) + " to get there.</em> <p></p>");
getDirections(json).forEach(function (item) {
$(div).append("<p>" + item + "</p>");
});
$("#listDirections").append(div);
}
$('#next').click(function() {
$('#tempDiv').animate({
opacity: 0, // animate slideUp
marginLeft: '-100%',
marginRight: '100%'
}, 'fast', 'linear', function() {
$(this).remove();
});
$('.container').append($("#origin"));
});
/*
$("#next").click(function() {
// $('#tempDiv').hide('slide', {direction: 'left'}, 500).fadeOut('fast');
$('#next').show('slide', {direction: 'left'}, 500);
});
*/
$(document).ready(function () {
"use strict";
$("#getButton").click(function () {
// Get the user input
var origin = $('#origin').val().replace(/ /g, "%20");
var destination = $('#destination').val().replace(/ /g, "%20");
// Create the URL
var URL = "https://maps.googleapis.com/maps/api/directions/json?origin=" +
"" + origin + "&destination=" + destination + "&key=" + APIKEY;
// Obtain json object through GET request
$.getJSON(URL, function (json) {
console.log(getEta(json));
console.log(getDirections(json));
showDirections(json);
});
});
});
If I've understood well your question, you want to remove an "old div" animating it to the left, and then you want to create a "new div" animating it from the right. This code will helps you with that task (The comments in the code will help you to understand it):
HTML Code:
<button id="btn">Create</button>
<div id="container"></div>
JavaScript Code:
var sum = 1;
//---Function to create divs to animate
function createDiv() {
//---Disable button
active(false);
//---Access to the slide div
var slide = $("#container .slide");
//---If slide exists
if (slide.length > 0) {
//---Dissapear the slide to the left
slide.animate({
"opacity": 0,
"right": "100%"
}, function() {
//---Delete slide
$(this).remove();
//---Create new slide
var slide = create();
//---Appear slide from the right
appearSlide(slide);
});
//---If the slide no exists
} else {
//---Create slide
var slide = create();
//---Appear slide from the right
appearSlide(slide);
}
}
//---Create slide function
function create() {
var slide = $("<div/>");
slide.addClass("slide");
slide.text("div " + sum);
$("#container").append(slide);
sum++;
return slide;
}
//---Appear slide from the right function
function appearSlide(slide) {
slide.animate({
"opacity": 1,
"right": "0"
}, function() {
//---Enable button
active(true);
});
}
//---Enable / disable button function
function active(state) {
$("#btn").prop("disabled", !state);
}
//---Create a div by default
createDiv();
//---Create a alide when press the button
$("#btn").on("click", createDiv);
jsfiddle