how to disable dragend animation in html5 - html

I created a draggable element by setting its draggable attribute. When I drop the element, there is an animation of the element snapping back to its origin position:
How can the snap-back animation be disabled? I tried calling preventDefault() on the dragend event, but it had no effect on the animation.
The following snippet shows the basics:
document.getElementById('test').addEventListener(
'dragend', evt => {
evt.preventDefault();
}
);
#container {
border: 1px solid black;
min-width: 300px;
min-height: 200px;
position: relative;
}
#test {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
top: 25px;
left: 40px;
}
<div id="container">
<div id="test" draggable='true'></div>
</div>
Not every browser will show the dragged #test jumping back to the original position.

In order to prevent the animation, you need the drop event to fire. For the drop event to fire, you need to call preventDefault() in the handler for dragover.
document.addEventListener('dragover', function(e) { e.preventDefault() })
Example in MDN docs shows the same thing: https://developer.mozilla.org/en-US/docs/Web/Events/drop#Example
An old blog post describing the quirks of HTML5 Drag and Drop API: https://www.quirksmode.org/blog/archives/2009/09/the_html5_drag.html

As was said earlier, you need to explicitly describe onDragOver handler on the parent's container (where you will drop your draggable element) and put .preventDefault() on event to prevent this animation.
Here is a simple React code example for better understanding of this mechanic (you can position the box inside the container by dragging it):
App.jsx
import './App.css'
const App = () => {
function handleDragOver(e) {
e.preventDefault()
}
function handleDrop(e) {
let box = document.getElementById('box')
if (box) {
box.style.top = e.clientY + 'px'
box.style.left = e.clientX + 'px'
}
}
return (
<div className="container" onDragOver={handleDragOver} onDrop={handleDrop}>
<div id="box" draggable></div>
</div>
)
}
export default App
App.css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100vw;
height: 100vh;
position: relative;
}
#box {
width: 100px;
height: 100px;
background-color: lightgreen;
position: absolute;
}

Related

Why does the condition in the function not work?

Why does the condition in the function not work?
Please tell me why the .not() condition does not work.
$(".one").not(".two").on("click", function() {
console.log("click one");
})
.one {
width: 500px;
height: 300px;
background: grey;
position: relative;
}
.two {
background: red;
position: absolute;
top: 20px;
right: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">
<input type="file" class="two">
</div>
That's because of event bubbling.
When you click on .two, as it is a child of .one, the click event happens also on .one
To prevent this, you can use event.stopPropagation() but it might not be the right choice as it - indeed - stops the event propagation to every other element, and this could not be desirable if there are other events you listen to in your code and introduce bugs. Stopping propagation of events is something that should be used carefully:
Dangers of stopping Event propagation
Pros/Cons of using e.stopPropagation()
Another - and in my opinion preferred - option is to use the event.currentTarget and event.target. The first is the element to which the event is attached (.one in your case). The second is the actual HTML element that has been clicked.
So, you can check if the event.target is two or one and code different behavior for each alternative.
$(".one").on("click", function(event) {
console.log("event.target is: ", event.target);
console.log("event.currentTarget is: ", event.currentTarget);
if ($(event.target).hasClass('two')) {
console.log("Mmh... you clicked two, please click one");
} else if ($(event.target).hasClass('one')) {
console.log("YEAH! You clicked one this time");
}
})
.one {
width: 500px;
height: 300px;
background: grey;
position: relative;
}
.two {
background: red;
position: absolute;
top: 20px;
right: 0px;
}
.as-console-wrapper { max-height: 4.5em !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">
<input type="file" class="two">
</div>
$(".two").on("click", function(e) {
e.stopPropagation();
})

hide element on scroll within div vuejs3

I'm trying to make an element hide on scroll within a div. I tried this tutorial https://codepen.io/neutraltone/pen/poobdgv, but it works when the complete window is scrolled. I could not make it work on the specific div.
mounted() {
this.lastScrollPosition = window.pageYOffset
window.addEventListener('scroll', this.onScroll)
},
beforeUnmount() {
window.removeEventListener('scroll', this.onScroll)
},
I'm using Vuejs 3. I think the problem is, that I can't specifically point to the div. I tried it with this.$ref.name (using ref="name" on the div), instead of window, but something is not adding up.
Thanks in advance!
You could listen for the scroll event on the div using the v-on:scroll listener (or shorthand (#scroll) and then do whatever you want in the handler (in this case checking for scroll position and then hiding the element):
<template>
<div class="scrollable-container" #scroll="scrollHandler">
<div class="content">
<div v-show="isVisible" class="to-hide">Scroll Me</div>
</div>
</div>
</template>
<script>
export default {
data: function() {
return {
isVisible: true
};
},
methods: {
scrollHandler(e) {
this.isVisible = e.target.scrollTop > 300 ? false : true
}
}
}
</script>
<style>
.scrollable-container {
height: 500px;
width: 300px;
margin: 200px auto;
overflow-y: scroll;
border: 1px solid black;
}
.content {
height: 1000px;
}
.to-hide {
min-height: 500px;
background-color: blue;
}
</style>

How to scroll a div to the bottom in componentDidMount(using react.js)?

I'm creating a chat app in react.js and I'm having trouble with setting a div element to be scrolled to bottom every componentDidMount call.
I've tried to use these line but it didn't work:
componentDidMount() {
var objDiv = document.getElementById("scrolling-div");
objDiv.scrollTop = objDiv.scrollHeight;
}
this is the div
<div className="scroll-chat h-def-chat" id="scrolling-div">...</div>
.h-def-chat {
height: calc(100vh - 140px);
}
.scroll-chat {
overflow-y: scroll;
overflow-x: hidden;
float: left;
}
.scroll-chat::-webkit-scrollbar-track {
border-radius: 10px;
background-color: #f2f2f2;
}
.scroll-chat::-webkit-scrollbar {
width: 10px;
background-color: #f2f2f2;
}
.scroll-chat::-webkit-scrollbar-thumb {
border-radius: 3px;
background-color: #ccc;
}
I expect the div to be scrolled down every time the component mounts
is there a solution?
thx, Guy
You simply need to to window.scrollTo function i.e
componentDidMount() {
var objDiv = document.getElementById("scrolling-div");
window.scrollTo(0, objDiv.scrollHeight);
}
It will let you to bottom of your div.
Here i made one codesandbox for refrence.
Note you dont need to add 0 in scrollTo function. Its totally upto you from where you want to scroll.

Vue.js: do not show element until it is in correct position

I am learning Vue and really enjoying it. I have a tab that I want fixed to the bottom of the browser window when the page loads. When a user clicks the tab, it will slide up to show some content.
Everything is working great. I am able to have the tab stick to the bottom of the page - and click events are working great as well.
The problem I am having is that I need to calculate the height of tab (and div) to set the CSS property correctly. When the page loads, you can see the tab slide down into place. I would like to hide the tab until everything has been calculated and it's in the correct place.
Here is what I'm using:
app.js
new Vue({
el: '#info',
delimiters: ['${', '}'],
data: {
active: false,
inactive: true,
styles: {
'bottom': 0
},
},
methods() {
toggle: function (event) {
event.preventDefault();
this.active = !this.active;
this.inactive = !this.inactive;
}
},
mounted() {
let tabHeight = this.$refs.infoTab.clientHeight;
let boxHeight = this.$refs.infoBox.clientHeight; // 473px
this.styles.bottom = -boxHeight + 'px';
}
});
HTML
<div class="info not-active" id="info" #click="toggle" ref="infoTab"
v-cloak
v-bind:class="{ active: active }"
v-bind:style="styles">
<!-- content -->
</div>
style.css
[v-cloak] {
display: none;
}
/* more classes */
.info {
width: 100%;
position: fixed;
&.inactive {
bottom: -100%;
}
&.active {
bottom: 0 !important;
}
}
I know I am close, I just don't want users to see the tab slide into place. It should just be there. I tried using the created hook, but clientHeight is not available.
Any suggestions are greatly appreciated!
I think you can solve this just using CSS, no need to use any of Vue's lifecycle hooks, I made a pen with a vanilla JS example:
let infoNode = document.getElementById('info');
infoNode.addEventListener('click', () => {
if (infoNode.style.top) {
// clear inline top style
infoNode.style.top = '';
} else {
// set top to client height + 2 * border thickness
infoNode.style.top = `calc(100% - ${infoNode.clientHeight}px - 4px)`;
}
});
#info {
font-size: 16px;
width: 200px;
border: 2px solid hsl(0, 0%, 80%);
padding: 8px;
border-radius: 4px;
cursor: pointer;
position: fixed;
/* 100% height of the viewport subtracting:
tab height: padding, margin, & font size */
top: calc(100% - (8px + 8px + 24px));
/* we center the tab horizontally here using
50% the width of the viewport - 50% the fixed
width of the tab */
left: calc(50% - 200px/2);
transition: top 0.5s;
}
.title {
font-size: 24px;
font-weight: 500;
margin-bottom: 8px;
display: block;
}
p {
margin: 0;
}
<div id="info">
<span class="title">Click on Me</span>
<p>
This is the content of the tab, isn't it great? I think so too, and it can be of any arbitrary length!
</p>
</div>
Basically the trick is to use calc with top instead of -100% with bottom for your positioning, then your tab is initially rendered in the correct position and you don't have to worry it being out of place when a visitor first loads your page.

Get away with built-in dragging html elements

I have a problem with html-objects that moving when I´m dragging them, you know the transparent "ghost" -copy of the element that appears when you holding down the mouse and drag it. My problem is that it interrupt my mouse event. I have a image that should be able to move inside a div when you dragging it with the mouse. I have to events for that, first one for mousedown that trigger mousemove-event, mousemove handles the movement of the image. mousedown is no problem but when I´m moving the mouse with the button down the transparent "ghost" - copy of the elements appear and interrupt my mousemove-event. Is that any one how knows how to get around or fix this thing?
Could you provide a sample?
From what it sounds like, the first thing to check is that the events are actually being hit. Writing messages out to console whenever each event fires should help prove or disprove that the events are occurring as-expected.
Then you start your mousemove event, set a timeout for the appended class 'hide' in 0 ms. Its work.
const dragAndDrop = () => {
const card = document.querySelector('.dragDrop');
const cells = document.querySelectorAll('.block');
const dragStart = function () {
// i added timeout for appended class
setTimeout(() => {
this.classList.add('hide');
}, 0);
};
const dragEnd = function () {
// i added timeout for appended class
setTimeout(() => {
this.classList.remove('hide');
}, 0);
};
const dragOver = function (event) {
event.preventDefault();
}
const dragEnter = function (event) {
event.preventDefault()
this.classList.add('hovered');
}
const dragLeave = function () {
this.classList.remove('hovered');
}
const dragDrop = function () {
this.append(card);
this.classList.remove('hovered')
}
cells.forEach((cell) => {
cell.addEventListener('dragover', dragOver);
cell.addEventListener('dragenter', dragEnter);
cell.addEventListener('dragleave', dragLeave);
cell.addEventListener('drop', dragDrop);
})
card.addEventListener('dragstart', dragStart);
card.addEventListener('dragend', dragEnd);
}
dragAndDrop()
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
width: 100%;
height: 100vh;
display: flex;
justify-content: space-around;
padding-top: 20px;
}
.block{
width: 100px;
height: 100px;
background-color: rgb(99, 99, 99);
display: flex;
justify-content: center;
align-items: center;
}
.card{
width: 80px;
height: 60px;
background-color: black;
cursor: grab;
}
.hide {
display: none;
}
.hovered {
background-color: rgb(254, 164, 164);
}
<div class="block">
<div draggable="true" class="drag dragDrop">
<div class="card"></div>
<div class="text">Hello, world</div>
</div>
</div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
I wrote this 12 years ago but if I remember right the solution was something like,
imageElement.addEventListener('dragover', function(e) {
e.preventDefault()
});
This should prevent the user from clicking and dragging on the image which means the browser won't add any visual effects.