How to Create a Draggable Element

How to Create a Draggable Element
Hostman Team
Technical writer
CSS HTML
15.01.2025
Reading time: 7 min

The term Drag-and-Drop refers to the action of moving items using the mouse. Most often, this action is associated with moving files into folders.

The ability to drag and drop blocks and elements from one section to another makes website builders like Tilda and Wix so convenient. These platforms allow users to create pages without any programming knowledge. The easy-to-use interface makes it possible to build a landing page in just a couple of hours. Today, we will show you how to create similar draggable elements.

How to Implement Drag and Drop Effect Using JavaScript

The first thing to note is that we will implement the drag-and-drop functionality without loading any frameworks or JavaScript libraries. For the desired result, knowledge of the browser API and support for the following versions is enough: Firefox 3.5+, Chrome 4, 9+, Safari 6+, Opera 12+.

Before writing the code, we must address two tasks:

  1. Determine what and where we are dragging (draggable element and dropzone).

  2. Decide what will happen to the dragged element once it is dropped.

As usual, events are triggered in the browser when the specified conditions are met. Now, let's take a closer look at the events that occur until the object reaches the target area.

Events

When dragging elements, seven events are triggered. Even though their functions are intuitive, it's important to understand the circumstances under which they are triggered.

  1. Dragstart: This event is triggered when the dragging of the element begins as soon as the mouse presses down on the element.
  2. Dragenter: This event is triggered when the dragged element enters the target area (object).
  3. Dragover: The Dragover event occurs when the dragged element is within the target object's area but has not yet been released.
  4. Dragleave: This event occurs when the dragged element leaves the target object while the mouse button is still held down.
  5. Drag: This event is triggered throughout the entire duration of the dragging process.
  6. Drop: If this event is triggered, the dragged element has been "dropped" when the mouse button is released.
  7. Dragend: This event signifies the end of the drag process (either the element has been successfully moved or the dragging action canceled).

This list of events is divided into two subgroups. Events #1, #5, and #7 apply to the dragged element, while the others are used for the target area. The events do not function the other way around and cannot occur simultaneously. Therefore, you need to determine what will happen on the screen when your element is dragged into the dropzone. 

Now, let's get to the practical implementation.

Step-by-Step Guide

Draggable elements can be blocks, images, or text. We’ll provide an example using a to-do list, where the draggable element will be labeled “TASK,” and the target area will be labeled “DONE.” There will be two <div> elements in the HTML markup since one is the draggable element and the other is the drop zone. You can create as many elements and drop zones as needed.

Step 1: Create the Draggable Element

Create an HTML file in the new project directory and place the basic code for a web page into it. Also, create a .css and .js files in the same folder. To ensure the styles are applied, include the link to the style.css file between the <head> tags and the link to script.js just before the closing <body> tag.

<!DOCTYPE html>
<html lang="en">
<head>
    <title> Example to Perform Drag and Drop</title>
    <link rel="stylesheet" href=" css/ style.css" />
  </head>
<body>
   <script src="script.js"></script>
  </body>
</html>

Now, you need to create the draggable element and the target zone. As mentioned earlier, place the draggable element called "TASK" and the drop zone (where it will be dropped) between the <body> tags. Also, make sure to enable element dragging by setting the draggable attribute to true. To disable dragging or set the default behavior, use draggable="false | auto".

<!DOCTYPE html>
<html lang="en">
<head>
    <title> Example to Perform Drag and Drop</title>
    <link rel="stylesheet" href=" css/ style.css" />
  </head>
<body>
<div class="parent">
  <div class="origin">
    <div      id="element-1"
      class="draggable-element"
      draggable="true"    >
      TASK
    </div>
  </div>
    <div    class="example-dropzone"  >
    DONE
  </div>
</div>
   <script src="script.js"></script>
  </body>
</html>

Copy the code into your file, save it, and you can close it.

Step 2: Style the Elements

As we all know, CSS (Cascading Style Sheets) offers many styling possibilities. Let's style each class individually.

.parent {
  border: 40px solid #DEB887;
  color: #800000;
  display: flex;
  font-family: verdana;
  font-weight: bold; } 
.origin {
  flex-basis: 100%;
  flex-grow: 3;
  padding: 5px; }
.draggable-element {
  background-color: #FFDEAD;
  font-family: verdana;
  font-weight: bold;
  margin-bottom: 5px;
  margin-top: 5px;
  padding: 5px; }
.dropzone {
  background-color: #FFEBCD;
  flex-basis: 100%;
  flex-grow: 2;
  padding: 5px;}

Since we’ve already linked the CSS file in our HTML, open the page in a browser. You'll see a prohibited sign if you try to grab the draggable element. This means dragging is not yet implemented, so let’s move to the next step.

Step 3: Triggering Events

Nothing will happen when we try to move the element without handling the drag-and-drop events. We’ll use HTML attributes to assign event handlers and trigger the drag operation with the format on{event}. Remember that the draggable element and the target zone have different events.

In our project, we will use the main event handlers:

  • The ondragstart event handler triggers when the dragstart event occurs on the draggable element.

  • As mentioned earlier, the dragover event refers to the drop zone. It is triggered when the dragged element moves within the target zone.

  • The ondrop event handler signals the completion of the drag operation, meaning when the dragged element is dropped into the drop zone.

To store data during the drag process, we’ll use the dataTransfer object. This object is linked to the Event object. You can use three methods of dataTransfer:

  • setData() – sets the data for the drag operation.

  • clearData() – removes all data when called.

  • getData() – returns all data set during the dragstart event.

Now, open the script.js file and create a corresponding function for each of the events that will be triggered.

Since our block contains text, we will use text/plain for dragging.

function onDragStart(event) {
 event
    .dataTransfer
    .setData('text/plain', event.target.id);
 
  event
    .currentTarget
    .style
    .backgroundColor = 'red';
}
function onDragOver(event) {
  event.preventDefault();
}
function onDrop(event) {
  const id = event
    .dataTransfer
    .getData('text');
const draggableElement = document.getElementById(id);
const dropzone = event.target;
dropzone.appendChild(draggableElement);
  event
    .dataTransfer
    .clearData(); }

We’ll apply the preventDefault() method to cancel the default browser behavior. This way, the events will only occur when the specific conditions are met. We will add three event handlers in the first and second <div> elements in the HTML file.

Final code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title> Example to Perform Drag and Drop</title>
    <link rel="stylesheet" href=" css/ style.css" />
  </head>
<body>
<div class="example-parent">
  <div class="example-origin">
    <div      id="draggable-1"
      class="example-draggable"
      draggable="true"
      ondragstart="onDragStart(event);"   >
      draggable
    </div>
  </div>
     <div    class="example-dropzone" 
               ondragover="onDragOver(event);"
               ondrop="onDrop(event);">
    dropzone
  </div>
</div>
   <script src="script.js"></script>
</body>
</html>

Conclusion

Our example demonstrated how to move elements using HTML Drag and Drop with pure JavaScript. By following this step-by-step approach, you can move on to implement larger projects (which can always be hosted on cloud servers like Hostman). Remember, in development, a well-thought-out graphical interface establishes effective communication between the user and the application or website.

CSS HTML
15.01.2025
Reading time: 7 min

Similar

CSS

Customizing Scrollbars in CSS

You can style scrollbars to be narrow or wide, change colors, or even hide them. This is a relatively simple task, but it comes with some challenges regarding cross-browser compatibility. Let's explore how to properly create a custom scrollbar. Suppose the project manager came up with an updated design for the website server page. The mockups show that the scrollbars have custom styles using corporate colors. It looks interesting, and now we need to figure out how to implement this scrollbar styling. The solution is quick. In 2018, the CSS Scrollbars specification was introduced, which defines how the scrollbar's appearance can be customized. This specification introduced two new properties that affect the visual style of the scrollbar: scrollbar-color — controls the color of the scrollbar. scrollbar-width — controls the width of the scrollbar. Customizing the scrollbar is now a five-minute task. Let’s check this in practice. Applying CSS Scrollbars Properties Before diving into how to style the scrollbars, let’s first understand their components. The operating system and browser do not matter here. All scrollbars have at least two elements: Thumb — the draggable part that allows us to scroll. Track — the area along which the thumb moves. Now, let’s apply some properties to style these elements. First, we will start with the width of the scrollbar. The scrollbar-width property has three possible values: auto — the default width. thin — a thin scrollbar. none — hides the scrollbar. You cannot specify the width in pixels or percentages. This restriction is in place to ensure consistency in how control elements are displayed across different browsers and operating systems — or, in simpler terms, to avoid a mess of custom solutions that could confuse users. The scrollbar-color property accepts two values: the first one sets the color of the thumb, and the second one sets the color of the track. The default value is auto, which tells the browser to use the default system settings. Let’s combine both properties and apply the following styling: body { scrollbar-width: thin; scrollbar-color: green black; } When you check this in a browser, you will see that the scrollbar on the page becomes thin and black and green. Cross-Browser Compatibility In the test environment, styling the scrollbar with scrollbar-color and scrollbar-width looks great. But before sending it to production, we need to check cross-browser compatibility — after all, not everyone uses the same browser. When we open the styled page in Safari, we notice that the scrollbar remains in its default style. To check our suspicions, let’s look up the support for the CSS Scrollbars properties on Can I Use. The situation is disappointing. Four years after the specification was introduced, the convenient scrollbar customization is still unavailable in this browser.  So, does this mean we won’t be able to implement the designed layout and will have to change everything? Don't worry, there’s a solution. To modify the appearance of the scrollbar in Safari, we can use pseudo-elements: ::-webkit-scrollbar — controls the entire navigation element. ::-webkit-scrollbar-track — controls the track. ::-webkit-scrollbar-thumb — controls the thumb (draggable part). Using pseudo-elements may seem like a hack, but there's no other option. Let’s add some styles for cross-browser compatibility: body::-webkit-scrollbar { width: 15px; /* Width of the entire navigation element */ } body::-webkit-scrollbar-track { background: #fff; /* Color of the track */ } body::-webkit-scrollbar-thumb { background-color: #050c26; /* Thumb color */ border-radius: 20px; /* Roundness of the thumb */ border: 3px solid #050c26; /* Thumb border styling */ } The obvious advantage of this approach is that we can explicitly set the width of the scrollbar. The large header will match the color of a very wide scrollbar. A separate specification for the scrollbar element doesn't offer this flexibility. The options are limited to either automatic width calculation or displaying a thin navigation element (as much as possible, considering system settings). The same goes for colors. With pseudo-elements, we can set not just colors but also gradients. Let’s slightly modify the thumb style: body::-webkit-scrollbar-thumb { background: linear-gradient(45deg, #EECFBA, #C5DDE8); /* Gradient effect */ border-radius: 20px; border: 3px solid #050c26; } Now, the thumb will have a gradient effect that changes colors. The downside is that this is outdated syntax. The CSS Scrollbars specification explicitly mentions that using prefixed pseudo-elements related to the scrollbar is considered incorrect. However, until other browsers support the new properties, we are forced to use prefixed pseudo-elements to maintain cross-browser compatibility. Conclusion For now, to create scrollbar styles, you still need to use both approaches — if cross-browser compatibility is important to you. However, when adding pseudo-elements, keep in mind that their use may soon become obsolete. According to modern standards, this is not the best solution for styling scrollbars. But aside from standards, there’s also the practical need, which forces us to make compromises.
16 January 2025 · 5 min to read
CSS

How to Change the Color of HTML Elements

When working with a webpage, you often need to enrich the markup by adding visual variety. This can be driven by design requirements or personal preferences. There are many ways to make a page more visually appealing, from font choices to the dynamic behavior of content when scrolling. One of the key graphic techniques is changing the background or text color on the page. Modern browsers allow you to flexibly choose background colors or combinations and specify the desired values in a format that suits you. Elements That Can Have Color Almost any HTML element can have its color. The color is applied in different ways depending on what exactly you want to color. For example, if you need to change the color of text in HTML, you can use the color attribute, and for borders around it, the border-color attribute. These attributes can be set either directly in the markup using HTML attributes or in a CSS file linked to the markup. When working with colors in HTML, elements can be roughly divided into two groups: text elements and block elements. In text elements, you set the color of the text and its styling, while in block elements, you set the background and border colors. Text Elements Text elements include, for example, paragraphs or input fields. For these elements, you can use several attributes for visual styling. Let's look at how to change the text color: color: This attribute is used to set the color of the text and any text decoration (such as underline, overline, etc.). background-color: In addition to changing the text color, it is often required to change the background color as well. This attribute is used for such cases. text-shadow: Sometimes, text design on the page requires a shadow. If the shadow color differs from the default, you can set it using the text-shadow attribute. text-decoration-color: When you set a color for a text element using the color attribute, the color is applied to the accompanying text decoration. But if you want to set a different color for underlining, for example, you can use this attribute. caret-color: In specific cases, you may need to style input fields (input, textarea) or elements with the contenteditable attribute. This attribute allows you to color the caret (the vertical cursor) that appears in the fields. Block Elements For block elements, such as div, you can flexibly set background and border colors regardless of the content inside the block. background-color: Adds a fill to the entire area of the block element. This attribute will help if you're wondering how to change the background color in HTML for the entire page. Just add the attribute to the body styles and specify the desired color. outline-color: Sets the color of the outline around the element if an outline style is specified with outline-style. border-color: Allows you to set the color for the borders around the block element. To set the color for each side — top, bottom, right, and left — use the attributes border-top-color, border-bottom-color, border-right-color, and border-left-color respectively. Other Elements In addition to the HTML elements mentioned above, you can also work with the visual design of the page using technologies such as SVG, Canvas, or WebGL. How to Change Text Color in CSS The first step in using color in your markup is to determine how to specify it so that the browser understands how to color the element.  The way you specify the color primarily depends on how specific or complex the color is. For instance, there’s a difference between using a basic color like blue or combining red, green, and blue in different proportions, potentially with transparency. Key CSS Keywords The simplest way to specify a color is by using a keyword, such as green or lightgrey. For example, to use black for text, you would write color: black;, and the browser will automatically understand the color to display. You can find a complete list of reserved color keywords in the documentation. RGB Model RGB stands for Red, Green, and Blue. When you specify a color using the RGB model, you define the color by mixing three primary colors: red, green, and blue. Like in a regular color palette, mixing these colors in varying proportions creates new combinations and shades. The three RGB values are integers between 0 and 255 or percentages from 0 to 100. For example, when you specify rgb(0, 0, 255), you will see the color blue in the browser. Modern browsers also support an extended version of RGB, called RGBA, where you can specify color transparency. This is done by adding a fourth value for transparency in percentage form. For example, blue with 50% transparency would be written as rgba(0, 0, 255, 0.5). HEX Representation A HEX color is a hexadecimal representation of the RGB model. The color code consists of three pairs of hexadecimal digits, each representing the red, green, and blue components respectively. For example, specifying #00ff00 will display green. If each color group contains identical characters (for example, #2211dff), you can use a shorthand representation — #21f. HSL System HSL stands for Hue, Saturation, and Lightness. In this system, the color is not determined by mixing the three parameters. Instead, each component is independent, which makes it easy to adjust the color's saturation or brightness while keeping the same hue. This system allows more control over the color's appearance without altering the basic tone.
09 January 2025 · 5 min to read
CSS

How to Change a CSS Background Image’s Opacity

In web design, achieving the desired visual effect often involves manipulating CSS properties. One common requirement is adjusting the opacity of a background image. Whether you’re a seasoned developer or just starting your design journey, mastering background opacity will empower you to craft stunning visuals that not only look great but also resonate with your audience. This article provides a comprehensive guide on how to achieve this, including various methods and best practices. Introduction to CSS Backgrounds CSS backgrounds are fundamental for creating visually appealing web pages. They can enhance the aesthetics of a website by adding images, colors, and patterns.  Key Components Background Color: You can pick any color to fill the background of an element (like a box or a whole page). For example, if you want a bright blue background, you’d use: background-color: blue; Background Image: Instead of just a plain color, you can use a picture as your background. This is like putting up a poster or a mural. You specify the image you want to use: background-image: url('your-image.jpg'); Background Size: This controls how the background image fits. You can make it cover the entire space or repeat like a pattern. For example: background-size: cover; /* Makes the image fill the entire space */ Background Position: This determines where the background image sits. You can center it, move it to the top, or place it wherever you like: background-position: center; Background Opacity: This controls how transparent or solid your background is. It’s like adjusting the brightness of a lamp. We’ll talk more on this in the next section. Understanding CSS Opacity Opacity is a CSS property that controls the transparency of an element. It can take a value between 0 (completely transparent) and 1 (completely opaque). When applied, this property affects both the element and its contents. Opacity refers to the transparency level of an element. It is defined using a value between 0 and 1: 0 means fully transparent (invisible). 1 means fully opaque (completely solid). Values between 0 and 1 create varying degrees of transparency. For example: .canvas { opacity: 0.2; /* 20% transparent */ } This can be useful for layering elements or softening backgrounds without completely obscuring them. Applying Opacity to an Entire Element The simplest way to change the opacity of a background image is by applying the opacity property directly to the element containing the background.  Be warned! It’s a naive approach. It’s quite limiting. Here’s how: <div class="container"> <h1>Mastering CSS Opacity</h1> <p>This text will also have reduced opacity.</p> </div> <style> .container { background-image: url('https://images.unsplash.com/photo-1470252649378-9c29740c9fa8?q=80&w=1470&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D'); /* Set the background size and position */ background-size: cover; background-position: center; /* Set the opacity of the entire element, including the background image */ opacity: 0.6; /* Set the padding to create some space around the text */ padding: 20px; width: 500px; height: 300px; } .container h1 { color: white; font-size: 36px; } .container p { color: white; font-size: 18px; } </style> This method will set the opacity for the entire element, including any text or content within it. This can be problematic if you want text to remain fully opaque. Use an img element This method allows you to achieve a layered effect while maintaining control over the image transparency. In this example, we will include a separate <img> tag inside a container. <div class="image-container"> <img src="https://images.unsplash.com/photo-1554322662-f8dc2222f79f?q=80&w=1574&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="Descriptive Text" class="background-image"> <div class="content"> <h1>Make Waves and Ride the Tide</h1> <p>Escape to the Endless Horizon.</p> </div> </div> <style> .image-container { position: relative; width: 100%; height: 400px; /* Adjust height as needed */ overflow: hidden; /* Ensures no overflow */ } .background-image { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; /* Ensures the image covers the entire container */ opacity: 0.7; /* Adjust the opacity here */ } .content { position: relative; /* Keeps content above the image */ z-index: 1; /* Ensures this content is on top */ color: blue; text-align: center; padding: 20px; } </style> As you can see, the image opacity is 70% but the text is fully opaque. Interestingly, this approach overcomes the limitation of first method. Set Background Opacity with Pseudo-elements CSS pseudo-elements enable you to insert content before or after an element's actual content, providing a way to enhance your design with additional visual elements or text.  How It Works Layering Backgrounds: By using ::before or ::after, you can create an additional layer behind your main content. This layer can be styled with a background color or image and adjusted for opacity, providing a visually appealing backdrop. Content Insertion: The content property allows you to insert text or other elements dynamically, enhancing the design while ensuring that the main content remains unaffected. <div class="hero"> <h1>How to adjust css background image opacity</h1> </div> <style> .hero { position: relative; /* Establishes a positioning context */ text-align: center; color: black; Height: 50vh; } .hero::before { content: ""; /* Required for pseudo-elements */ position: absolute; /* Positions the background layer */ top: 0; left: 0; right: 0; bottom: 0; background-image: url('https://images.unsplash.com/photo-1705668403533-3c17914a497a?q=80&w=1506&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D'); background-size: cover; /* Ensure the image covers the area */ opacity: 0.5; /* Adjusts the opacity of background css */ z-index: 0; /* Places it behind the content */ } .hero h1 { position: relative; z-index: 1; /* Text appears on top */ padding: 20px; } </style> That’s the benefit you can get using pseudo-elements. You can achieve complex designs without adding extra divs or elements to your HTML, keeping your markup minimal and organized. Explanation Positioning: The .hero class is set to relative, which creates a positioning context for the pseudo-element. The ::before pseudo-element is absolutely positioned to cover the entire .hero container. Background Layer: The ::before pseudo-element contains a background image with adjusted opacity. This creates a semi-transparent effect, allowing the background image to be visible but softened. Text Visibility: The heading (h1) is given a higher z-index to ensure it appears above the semi-transparent background, making it easy to read. Best Practices When working with CSS background opacity, keep the following best practices in  mind: Utilize ::before and ::after pseudo-elements. Avoid using opacity on elements with text or other content, as it can affect readability. If you’re working with solid colors, consider using RGBA (Red, Green, Blue, Alpha) values for transparency. This allows for fine-tuned control over color and opacity without affecting other properties. background-color: rgba(255, 0, 0, 0.5); /* Red with 50% opacity */ Use viewport units (like vh or vw) to make backgrounds responsive. This ensures that backgrounds scale appropriately on different screen sizes. Test your design in different browsers and devices to ensure com Final Thoughts Incorporating CSS background opacity effectively can transform your design, making it not only visually appealing but also functional. By leveraging transparency, you can create a polished and professional look that enhances user experience and engagement.
07 October 2024 · 7 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support