Draggabilly: dragged elements in wrong position - javascript

i want to create a page with two areas. On the left is an "asset"-area, on the right the "content"-area. I have multiple elements in the "asset"-area. If i drag an element, it should be droppable in the right area.
I'm using the "draggabilly" library for simplicity. If i drag and drop an element, a copy of the original element should be created. This is fine. But if i drop an element, the element doesn't appear on the position of the mouse. Instead, it appears on other positions on the page.
I've got the following code:
HTML
<h2>Assets</h2>
<div id="tool-box">
<!--<img src="https://via.placeholder.com/100x100" draggable="true" ondragstart="drag(event)">-->
<!--<div id="clone-container"></div>-->
<img src="https://via.placeholder.com/100x100" class="draggable">
<div class="draggable"></div>
<div class="draggable"></div>
<div class="draggable"></div>
<div class="draggable"></div>
</div>
</div>
<!-- Main Panel -->
<div>
<h2>Editor</h2>
<div id="box-content">
<!--<div id="test1" class="content" ondrop="drop(event)" ondragover="allowDrop(event)""></div>-->
<div class=" content">b</div>
<div class="content">c</div>
<div class="content">d</div>
</div>
JS
const draggableElems = document.querySelectorAll('.draggable');
const cloneContainer = document.querySelector("#box-content");
draggableElems.forEach(element => {
const draggable = new Draggabilly(element);
draggable.on('dragStart', function() {
const clone = element.cloneNode(true);
clone.classList.add('clone');
clone.style.position = "absolute";
clone.style.left = `${element.offsetLeft}px`;
clone.style.top = `${element.offsetTop}px`;
document.body.appendChild(clone);
draggable.element = clone;
const draggableClone = new Draggabilly(clone);
});
draggable.on('dragMove', function(event) {
draggable.element.style.left = `${pointer.pageX}px`;
draggable.element.style.top = `${pointer.pageY}px`;
});
CSS
body { font-family: sans-serif; }
.draggable {
width: 140px;
height: 140px;
background: #000FFF;
border-radius: 10px;
cursor: move;
}
.draggable.is-pointer-down {
background: #09F;
}
.draggable.is-dragging { opacity: 0.7; }
I tried several code for the position, but none works as expected.
Do you have any clue, why the elements appear on the wrong position and how to fix it?
Thanks!

Related

Two Column Accordion with Separate Full Width Divs

The intension is to have a two column accordion, without limiting the "expand" field to the left or right column. The catch is that there will be multiple on one page. This is already created, but only button 1 is working. With the way my JS is going, it will get very very repetitive - I am looking for assistance with re-writing the JS to be multiple click friendly. Fiddle: https://codepen.io/ttattini/pen/abLzaaY
EDIT: It would also be perfect if one dropdown would close as the next is opened
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="row">
<div id="column">
<button id="button">I am Button #1</button>
<button id="button">I am Button #3</button>
</div>
<div id="column">
<button id="button">I am Button #2</button>
<button id="button">I am Button #4</button>
</div>
</div>
<div id="hidden">
<p id="content"> So here I am #1</p>
</div>
<div id="hidden">
<p id="content"> So here I am #2</p>
</div>
<div id="hidden">
<p id="content"> So here I am #3</p>
</div>
<div id="hidden">
<p id="content"> So here I am #4</p>
</div>
CSS
#hidden {
background: #ccc;
margin-top: 2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
#button {
padding: 10px;
margin-top: 5px;
width:50%;
margin-left: 10%;
cursor: pointer;
}
#row {
display: flex;
}
#column {
flex: 50%;
}
JS
$(function() {
var b = $("#button");
var w = $("#hidden");
var l = $("#content");
b.click(function() {
if (w.hasClass('open')) {
w.removeClass('open');
w.height(0);
} else {
w.addClass('open');
w.height(l.outerHeight(true));
}
});
});
The biggest issue is that you're using IDs when you should be using classes. IDs must be unique to each element in a page. When you repeat an ID, JS will only target the first element using that ID. That's why only the first one is working.
The second issue is that, because of the way the script is written, it will only target a single element. What you need to do is get all the elements you want to target by something like their class name and then loop through them, applying the event listener to each one and its appropriate children.
EDIT: Here is an example from some code I wrote for a page with multiple accordions a few weeks ago in vanilla JS
//Below I establish a counting variable and find all the accordions on the page
const acc = document.getElementsByClassName( 'accordion' );
let i;
//Looping through each accordion
for ( i = 1; i <= acc.length; i++ ) {
//Identify target for the event listener. In this case, a heading for each accordion, which I've numbered e.g. "title-1"
const title = 'title-' + i;
const label = document.getElementById( title );
//Identify target content, in this case a list that has a unique ID e.g. "list-1"
const listNum = 'list-' + i;
const list = document.getElementById( listNum );
//Add event listener to heading that toggles the active classes
label.addEventListener( 'click', function() {
label.classList.toggle( 'accordion--active' );
});
}
Of course, there's more than one way to skin a cat, but this is a working example.
I have tracked the clicked event of each button and showed the corresponding hidden content with the use of data- attribute.
I have used vanilla JavaScipt instead of jQuery.
const buttons = document.querySelectorAll('.button');
const hiddens = document.querySelectorAll('.hidden');
buttons.forEach((btn) => {
btn.addEventListener('click', btnClicked)
function btnClicked(e) {
hiddens.forEach((hidden) => {
if(e.target.dataset.btn == hidden.dataset.content) {
hidden.classList.toggle('height')
} else {
hidden.classList.remove('height')
}
})
}
})
.hidden {
background: #ccc;
margin-top: 2%;
padding-left:2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
.hidden.height {
height: 50px;
}
.button {
padding: 10px;
color: white;
background-color: #2da6b5;
border: none;
margin-top: 5px;
width:90%;
margin-left: 5%;
cursor: pointer;
}
.button:hover {
filter: brightness(.9);
}
#row {
display: flex;
}
.column {
flex: 50%;
}
<div id="row">
<div class="column">
<button class="button" data-btn="one">I am Button #1</button>
<button class="button" data-btn="three">I am Button #3</button>
</div>
<div class="column">
<button class="button" data-btn="two">I am Button #2</button>
<button class="button" data-btn="four">I am Button #4</button>
</div>
</div>
<div class="hidden" data-content="one">
<p class="content"> So here I am #1</p>
</div>
<div class="hidden" data-content="two">
<p class="content"> So here I am #2</p>
</div>
<div class="hidden" data-content="three">
<p class="content"> So here I am #3</p>
</div>
<div class="hidden" data-content="four">
<p class="content"> So here I am #4</p>
</div>
Also, please do not use the same ID at multiple elements.

Add prev/next buttons to scroll container with CSS and jQuery

After a long research I found a solution to add a custom scrollbar to a DIV element.
It's called SimpleBar. Docs can be found here.
The HTML structure and JS code is pretty simple:
Working demo
<div class="gallery" data-simplebar data-simplebar-auto-hide="false">
<div class="item"><img src="https://via.placeholder.com/250x150/0000FF" /></div>
<div class="item"><img src="https://via.placeholder.com/350x150/FF0000" /></div>
[...]
</div>
With data-simplebar I can add a custom scrollbar to any DIV.
There is just one thing I couldn't solve.
I want to add prev/next arrows to the scroll element.
The buttons should jump to the prev/next element in the DIV which is next to the left/right side of the div and not yet scrolled (partially) over.
And the JS should work for every slider instance on the site. Like the SimpleBar itself. There is no need for extra code per scroll container.
Is there anything I could use in jQuery?
EDIT: I found this answer and fiddle. I added the code to my example and changed it to left/right. It's not exactly what I need but I thought it could be a starting point. Unfortunately it doesn't work properly.
You can use the following code. Note that the scrolling depends on the viewport, so that once there's no more right width to go to, it won't have more room to move.
const DIRECTION = { PREV: 1, NEXT: 2 };
$(document).ready(function () {
$('.container').each(function (index, containerItem) {
var $gallery = $(containerItem).find('.gallery');
const simpleBar = new SimpleBar($gallery[0], {
autoHide: false,
scrollbarMaxSize: 50
});
var $scroller = $(simpleBar.getScrollElement());
$(containerItem).find('.scrollLeft').on('click', function () {
scroll(DIRECTION.PREV, $scroller);
event.preventDefault(); // prevents anchor jump on click
});
$(containerItem).find('.scrollRight').on('click', function () {
scroll(DIRECTION.NEXT, $scroller);
event.preventDefault();
});
$scroller.scroll(function () {
setButtonsVisibility($scroller);
});
});
});
function scroll(direction, $scroller) {
var $active = $scroller.find('.active');
var $target = direction == DIRECTION.PREV ? $active.prev() : $active.next();
if ($target.length) {
$scroller.animate({
scrollLeft: $target[0].offsetLeft
}, 2000);
$active.removeClass('active');
$target.addClass('active');
}
}
function setButtonsVisibility($scroller) {
var scrollLeft = $scroller.scrollLeft();
isScrollerStart($scroller, scrollLeft);
isScrollerEnd($scroller, scrollLeft);
}
function isScrollerStart($scroller, scrollLeft, $button) {
var $prevButton = $scroller.closest('.container').find('.scrollLeft');
if (scrollLeft == 0) {
$prevButton.css('visibility', 'hidden');
} else {
$prevButton.css('visibility', 'visible');
}
}
function isScrollerEnd($scroller, scrollLeft) {
var $nextButton = $scroller.closest('.container').find('.scrollRight');
var scrollWidth = $scroller[0].scrollWidth; // entire width
var scrollerWidth = $scroller.outerWidth() // visible width
if (scrollLeft >= scrollWidth - scrollerWidth) {
$nextButton.css('visibility', 'hidden');
} else {
$nextButton.css('visibility', 'visible');
}
}
.container {margin: 0 auto 2rem; max-width: 960px;}
.gallery {padding-bottom: 2rem; margin-bottom: 2rem;}
.gallery .simplebar-content {display: flex;}
.gallery .item {margin-right: 1rem;}
.simplebar-scrollbar:before {background: red !important;}
.simplebar-track.simplebar-horizontal {background: #eee !important;;}
.buttons {display: flex; justify-content: space-between; width: 100%; margin-bottom: 2rem;}
.buttons a {padding: 0.5rem; background: #ddd; text-decoration: none; color: #000;}
.scrollLeft { visibility: hidden; }
<script src="https://unpkg.com/simplebar#latest/dist/simplebar.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/simplebar#latest/dist/simplebar.css">
<div class="container">
<h2>Slider</h2>
<div class="gallery">
<div class="item active"><img src="https://via.placeholder.com/150x30/110000" /></div>
<div class="item"><img src="https://via.placeholder.com/450x30/3300FF" /></div>
<div class="item"><img src="https://via.placeholder.com/350x30/992244" /></div>
<div class="item"><img src="https://via.placeholder.com/400x30/0000FF" /></div>
</div>
<div class="buttons">
<a class="scrollLeft" href="#"><strong>Prev</strong> (remove if first)</a>
<a class="scrollRight" href="#"><strong>Next</strong> (remove if last)</a>
</div>
</div>
<div class="container">
<h2>Slider</h2>
<div class="gallery">
<div class="item active"><img src="https://via.placeholder.com/150x30/110000" /></div>
<div class="item"><img src="https://via.placeholder.com/450x30/3300FF" /></div>
<div class="item"><img src="https://via.placeholder.com/350x30/992244" /></div>
<div class="item"><img src="https://via.placeholder.com/400x30/0000FF" /></div>
</div>
<div class="buttons">
<a class="scrollLeft" href="#"><strong>Prev</strong> (remove if first)</a>
<a class="scrollRight" href="#"><strong>Next</strong> (remove if last)</a>
</div>
</div>

Press a button and change the color of box elsewhere on page [duplicate]

This question already has answers here:
How to change div background color on button click?
(2 answers)
Closed 3 years ago.
I'm very new to coding and have learned my very limited knowledge from forums and tutorials online. I seem to be up against a problem that I cannot for the life of me figure out.
My goal is to press one of three buttons (Leadership, Program, Team) at the top of a grid (the grid lists our services) and have the appropriate grid box change colors. For example, pressing the Leadership button would turn a grid box blue, Program would turn a grid box yellow, and Team would turn a grid box green. This means that a grid box might be linked to more than one of the buttons, as our services overlap. So depending on what button is pressed, a single grid box might change to blue, yellow, or green.
I figured out how to do toggle buttons which show the body onclick. BUT that means A LOT of redundancy. (I would have to do a grid with the appropriately colored boxes for Leadership, another one for Program, and another one for Team). So, I think I'm on the wrong path there.
I've searched toggles, buttons, anchors, event listeners, targets, you name it. It seems like it all relates to the button itself, not how the button relates to an element on the page.
I am very grateful to anyone who can point me in the right direction! Thank you!
function goToAnchor(anchor) {
var loc = document.location.toString().split('#')[0];
document.location = loc + '#' + anchor;
return false;
}
var divs = ["Div1", "Div2", "Div3", "Div4"];
var visibleDivId = null;
function divVisibility(divId) {
if(visibleDivId === divId) {
visibleDivId = null;
} else {
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs() {
var i, divId, div;
for(i = 0; i < divs.length; i++) {
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
}
.square-grey {
display: table-cell;
height: 100px;
width: 600px;
text-align: center;
vertical-align: middle;
border-radius: 5%;
/*make it pretty*/
background: #F5F5F5;
color: #999999;
padding: 10px 15px 10px 15px;
font: 20px "helvetica";
font-weight: 350;
box-shadow: 2px 3px 3px #999999;
}
div.highlit {
padding: 25px;
}
<div class="row">
<div class="buttons">
<div style="text-align:center">
<div class="col-sm-4">
Enterprise
</div>
<div class="col-sm-4">
Program
</div>
<div class="col-sm-4">
Team
</div>
</div>
</div>
</div>
<div class="inner_div">
<div id="Div1">
<div class="row">
<div style="text-align:center">
<div class="col-sm-3">
<div class="top-buffer">
<div class="square-grey">
Strategic Alignment
</div>
</div>
</div>
<div class="col-sm-3">
<div class="top-buffer">
<div class="square-grey">
Adaptive Leadership
</div>
</div>
</div>
<div class="col-sm-3">
<div class="top-buffer">
<div class="square-grey">
Portfolio Management
</div>
</div>
</div>
<div class="col-sm-3">
<div class="top-buffer">
<div class="square-grey">
Cultural Shift
</div>
</div>
</div>
</div>
</div>
</div>
<div id="Div2" style="display: none;">I'm Div Two</div>
<div id="Div3" style="display: none;">I'm Div Three</div>
</div>
</div>
Edited answer, you can add IDs to the boxes and pass them to function.
const changeColor = (elements, color) => {
elements.forEach(el => {
const element = document.querySelector(el);
element.style.backgroundColor = color;
})
}
.colorbox {
width: 100px;
height: 100px;
background-color: aquamarine;
margin-bottom: 10px;
}
<div class="colorbox" id="colorbox1"></div>
<div class="colorbox" id="colorbox2"></div>
<div class="colorbox" id="colorbox3"></div>
<button onclick="changeColor(['#colorbox1', '#colorbox3'], 'tomato')">Change 1 & 3 to tomato</button>
<button onclick="changeColor(['#colorbox1', '#colorbox2'], 'aliceblue')">Change 1 & 2 to aliceblue</button>
<button onclick="changeColor(['#colorbox2', '#colorbox3'], '#ff0000')">Change 2 & 3 to reddest</button>

Dynamically change nth-child number

ngx-datatable > div > datatable-body > datatable-selection:hover > datatable-scroller > datatable-row-wrapper:nth-child(n) > datatable-body-row > div.datatable-row-center.datatable-row-group > datatable-body-cell:nth-child(1) {
background-color: #E9F1FA !important;
}
This is my long selector. I am trying to highlight the entire column based on the user hovering over an item on a column. This works great, except that it only highlights whatever nth-child I am using on the last datatable-body-cell:nth-child(1) I can change it to any number and it works, but it isn't dynamic. I want it to only select the column that is being hovered over. I've tried datatable-body-cell:nth-child(n):hover and datatable-body-cell:hover and a lot of different varieties but it either highlights the whole table, or nothing at all, unless I specify the nth-child.
Is there a way I can dynamically change the nth-child based on the what child the user is hovering over (with CSS or Javascript)?
Any help would be appreciated!
You can use document.querySelector to get the column and set its style it is being hovered over on mouseenter and reset it back to normal on mouseleave.
var n = 1;//the number
document.querySelector('ngx-datatable > div > datatable-body > datatable-selection:hover > datatable-scroller > datatable-row-wrapper:nth-child('+n+') > datatable-body-row > div.datatable-row-center.datatable-row-group > datatable-body-cell:nth-child(1)').style.setProperty('background-color', '#E9F1FA', 'important');
Demo:
var children = document.querySelectorAll('div.child');
Array.prototype.slice.call(children).forEach(function(child){
var n = child.parentNode.getAttribute('data-num');
var parent = document.querySelector('div.table>div:nth-child('+n+')');
child.addEventListener('mouseenter', function(e){
parent.style.backgroundColor = "yellow";
this.style.backgroundColor = "red";
});
child.addEventListener('mouseleave', function(e){
var n = +this.parentNode.getAttribute('data-num');
parent.style.backgroundColor = "";
this.style.backgroundColor = "";
});
});
.table{
height: 250px;
width: 400px;
margin: 5px;
padding: 5px;
background-color: goldenrod;
}
.column{
background-color: dodgerblue;
margin: 5px;
}
.child{
border: 1px solid black;
}
<div class="table">
<div class="column" data-num="1">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
</div>
<div class="column" data-num="2">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
</div>
<div class="column" data-num="3">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
</div>
</div>

Getting divs next to each other when clicking on a button / JQuery

i am making a kind of storyboard where you can add and remove frames but i need to set divs next to each other, the code i now have it places the div's beneath each other. I want to make it with a loop
Here is my code:
HTML
<div id="storyboard">
<div id="container">
<div class="frame">
<div class="frame__outer">
<div class="frame__inner"></div>
<div class="frame__content"></div>
<div type="button" value="fade_in" class="add__button"> + </div>
</div>
</div>
</div>
</div>
JS
_this.addClickFunction = function() {
var i = 0;
$('.add__button').click(function() {
$('.frame').after('<div id="container'+(i++)+'"></div> <div class="frame__outer"> <div class="frame__inner"></div><div class="frame__content"></div></div>');
});
};
Use append() instead of after() function. This should work:
_this.addClickFunction = function() {
var i = 0;
$('.add__button').click(function() {
$('.frame').append('<div id="container'+(i++)+'"></div> <div class="frame__outer"> <div class="frame__inner"></div><div class="frame__content"></div></div>');
});
};
This works for keeping one .frame element and adding multiple divs to it of the structure:
<div class="container[i]">
<div class="frame__outer">
<div class="frame__inner"></div>
<div class="frame__content"></div>
</div>
</div>
If you want to arrange elements side by side which normaly are block elements and thus are positioned underneath eachother by default use either css floats or css flexbox.
https://css-tricks.com/all-about-floats/
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
i need to set divs next to each other
Try this example to add new story container to all current .container
var i = 1;
$('.add__button').click(function() {
i++;
$(".container").each(function(x) {
$(this).after('<div id="container' + x + '_' + i + '" class="container"><div class="frame"><div class="frame__outer"> <div class="frame__inner"></div><div class="frame__content">story ' + i + '</div></div></div></div>');
});
});
.frame__outer {
padding: 20px;
background: #222;
color: white;
border-bottom: solid 3px green;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="storyboard">
<input type='button' value='add story' class="add__button" />
<div id="container" class='container'>
<div class="frame">
<div class="frame__outer">
<div class="frame__inner"></div>
<div class="frame__content">story 1</div>
</div>
</div>
</div>
</div>

Categories