How to create a draggable HTML element in a website ?
What is draggable element in a website ?
A draggable element refers to a HTML element in a webpage which you can move by dragging through the mouse pointer to any position on the screen. You may have seen draggable elements in webpages in the form of Contact form, or Live chat, or Menus etc.
What is the need of draggable elements in webpage ?
The main need behind a draggable element in a website is users' interaction, which leads to good user experience and better connection of your site with the user.
Indirectly, it helps to increase view time of your site. Also a draggable element is easy to access from every page, you need not to go to other page to use that. That's why, it is very useful to put your business products in a draggable element, so that audience can easily interact. You can think of many such possibilities of using a draggable element.
How to create a draggable element ?
Firstly and obviously, you need to create an element in the HTML page. For that element to work as a draggable element you need to make it position:fixed in CSS.
Now, to make it draggable we will first listen to any click on that element using JavaScript click event. If it is clicked and user moves mouse pointer, we will listen that using mousemove event. So, if user moves the mouse along with clicking on the element, we will change the position of that element with respect to the mouse pointer's position on the screen. Like this, the user can put that element anywhere on the screen. Now as soon as user releases the mouse click, then the element will stop in its place even if mouse is moved. This will be the main scenario. I will only provide the javascript code with a function called draggable(). We need to pass the draggable element's id to this function to make it draggable in JavaScript.
function draggable(id) {
let box = document.getElementById(id);
let clicked = false;
box.onmousedown = ()=> {
clicked = true;
};
document.onmouseup = ()=> {
clicked = false;
};
document.onmousemove = (e)=> {
if (!clicked) return;
if (!(e.clientX < box.clientWidth / 2 || e.clientX > screen.width - box.clientWidth / 2)) {
box.style.left = e.clientX - box.clientWidth / 2 + "px";
}
if (!(e.clientY < box.clientHeight / 2 || e.clientY > screen.height - box.clientHeight / 2)) {
box.style.top = e.clientY - box.clientHeight / 2 + "px";
}
};
}
Now, let's suppose the id of your element is "box". Then you have to call the function like draggable("box"); And then open the HTML page in browser, you will find your element as draggable. To Be noted -- Your element must be position:fixed.
Okay, if you are reading until now, cheers, you now know how to create a draggable element in webpage. What are you waiting for then ? Go implement it in your site in local machine or live server. Hope you have understood the code and explanation, I have given. Okay, that's all for this post. See you soon.
Comments
Post a Comment