How to Create Scrolling on Your Website Using CSS

How to Create Scrolling on Your Website Using CSS
Hostman Team
Technical writer
CSS HTML
20.01.2025
Reading time: 8 min

Do you want to add parallax and scrolling effects to your page but don’t know where to start? You don’t need to jump straight into JavaScript—simpler options are available. In this article, we’ll explain how to achieve this using CSS alone and clarify which browsers might not support these effects.

Smooth Scrolling

To create simple scrolling from one part of the page to another, use the CSS property scroll-behavior

Use the CSS property scroll-behavior to create simple scrolling from one part of the page to another. Here are its main values:

  • auto: The default behavior.

  • smooth: Enables smooth transitions.

  • instant: Enables quick transitions.

Here’s what CSS code looks like with the second value (smooth) applied to a conditional p selector:

p {
  scroll-behavior: smooth;
}

Next, we’ll demonstrate how to create a smooth transition from one part of a site to another using the smooth value. In this example, the user will see the transition when clicking a hyperlink that leads to another section of the page.

Step 1. Create two blocks with links to each other:

<html>
<body>
<head></head>

<h1>Smooth Scrolling</h1>

<div class="main" id="block1">
  <h2>Block 1</h2>
  <p>Click the hyperlink to see smooth scrolling.</p>
  <a href="#block2">Click here to go to Block 2.</a>
</div>

<div class="main" id="block2">
  <h2>Block 2</h2>
  <a href="#block1">Click here to go to Block 1.</a>
</div>

</body>
</html>

66f1fd39 E0d5 44e0 8c05 51e0a465394b

Step 2. Add smooth scrolling using CSS code inside the <head> tag. The code will include the scroll-behavior property with the value smooth. Additionally, set colors and heights for the different text sections: pink and yellow.

<head>

<style>
html {
  scroll-behavior: smooth;
}

#block1 {
  height: 1000px;
  background-color: #ffa3f6;
}

#block2 {
  height: 1000px;
  background-color: #fffc9c;
}
</style>

</head>

Chrome Capture 2024 12 28

Thanks to the smooth value, smooth scrolling is implemented on the web page.

If You Need Parallax

Parallax is an effect where background elements move faster or slower than objects in the foreground. For example, as a user scrolls a page, the background image may move at one speed while the text moves at another.

In this case, we’ll ensure the background image doesn’t move at all during scrolling.

Step 1. Write the HTML code, which includes a large purple text block:

<html>
<head></head>

<body>

<h1>Scroll Further Down the Page</h1>

<div class="paral"></div>

<div style="height:550px;background-color:#bf89e0;font-size:50px">
This text is included simply to demonstrate the effect. Try scrolling up and down. The text block will move, but the image will remain stationary.
</div>

<div class="paral"></div>

</body>
</html>

Step 2. Add the CSS code. It will include a link to an image that becomes the background using the background-attachment: fixed property.

<style>

body, html {
  height: 90%;
}

.paral {
  background-position: center;
  background-attachment: fixed;
  background-size: cover;

  background-image: url('https://images.unsplash.com/photo-1519681393784-d120267933ba?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2070&q=80');
  
  height: 90%;
}

</style>

As a result, the parallax effect is implemented on the page.

Parallax

Note. To remove this effect, simply replace background-attachment: fixed with background-attachment: scroll in the code. The image will then move along with the text.

Background Scroll

Additional Examples

To better understand CSS properties, let’s explore other scrolling effects for a website.

Example 1

Here’s a step-by-step guide to achieving a multi-layered scrolling effect. In this case, multiple objects on the site will move at different speeds during scrolling.

Step 1. Write two sections in the following way:

<html>
<head></head>

<body>
<section class="block1">
  <h1>Block 1</h1>
</section>
<section class="block2">
  <h1>Block 2</h1>
</section>
</body>
</html>

1b43d38b 5e6d 42c6 A67f 119ec8886735

Step 2. Add CSS code inside the <head> tag. First, define the parameters and select a background from a free photo stock for Block 2:

<head>
<style>
section {
  position: absolute;
  min-height: 90vh;
  width: 100%;
  transform-style: inherit;
  position: relative;
}

.block1 {
  z-index: 2;
  background: #ff9012;
}

.block2::before {
  background: url(https://images.unsplash.com/photo-1536308037887-165852797016?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=826&q=80) top center;
  content: '';
  top: 0; left: 0; right: 0; bottom: 0;
  position: absolute;
  display: block;
  transform: translateZ(-0.5px) scale(2);
  z-index: -2;
  background-size: cover;
}
</style>
</head>

Step 3. Specify the parameters for the headings:

<head>
<style>
h1 {
  font-size: 3.7rem;
  position: absolute;
  padding: 0.8rem;
  background: #fffcfc;
  transform: translateZ(-1px) scale(1) translate(-25%, -25%);
  top: 49%;
  left: 49%;
  text-align: center;
}

.block1 h1 {
  z-index: 2;
  transform: translate(-49%, -49%);
}

.block2 h1 {
  z-index: 2;
  transform: translateZ(-0.4px) scale(1.2) translate(-39%, -39%);
}
</style>
</head>

Step 4. Define the parameters for other elements:

<head>
<style>
*,
*::before,
*::after,
:root {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

html {
  height: 95%;
  overflow: hidden;
}

body {
  height: 95%;
  overflow-x: hidden;
  overflow-y: scroll;
  perspective: 0.8px;
  transform-style: preserve-3d;
  font-size: 40%;
  font-family: 'PT Astra Sans';
}
</style>
</head>

Example

As a result, the website will have three moving objects. Here they are, ranked from slowest to fastest:

  1. The background image of Block 2.

  2. The "Block 2" heading.

  3. Block 1 with the orange background.

This is how multi-layered scrolling looks in action.

Example 2

Let’s look at how to fix an element on a webpage during scrolling. For instance, hostman.com has such pinned elements:

Image3

Step 1. Write HTML with two text blocks like this:

<html>
<head></head>

<body>
<h1>Fixed Element</h1>
<div class="extra"></div>

<div class="wrap">
  <div class="elem">
    Element
  </div>
</div>
</body>
</html>

Step 2. Add the following CSS inside the <head> tag:

<head>
<style> 
body {
  font-family: Times New Roman;
}

h1 {
  text-align: justify;
}

.wrap {
  background-color: #52ff83ab;
  width: 90%;
  height: 2000px;
  margin: 30px;
}

.elem {
  background: #6052ff;
  width: 150px;
  height: 150px;
  color: #fcfcfc;
  align-items: center;
  justify-content: center;
  display: flex;
  position: fixed;
}
</style> 
</head>

Image2

When using the position: fixed property, the element remains visible and moves along with scrolling.

Example 3

This time, let’s create horizontal scrolling.

Step 1. Create four text blocks like this:

<html>
<head></head>

<body>
<div id="container">
  <div id="container2">
    <div class="type one"><div>One</div></div>
    <div class="type two"><div>Two</div></div>
    <div class="type three"><div>Three</div></div>
    <div class="type back"><div>Four</div></div>
  </div>
</div>
</body>
</html>

Image9

Step 2. Add the following CSS inside the <head> tag. This code defines the size and color of the text blocks:

<head>
<style> 
body {
  font-family: PT Astra Sans;
  margin: 0;
}

#container .type {
  position: relative;
  display: inline-block;
  width: 150vw;
  height: 99vh; 
}

#container .type > div {
  position: relative;
  width: 99px;
  height: 99px;
  color: #080808;
  line-height: 0.8;
  top: 48%;
  left: 48%;
  font-weight: bold;
  font-size: 96px;
}

#container {
  position: absolute;
  overflow-x: scroll;
  overflow-y: scroll;
  transform: rotate(270deg) translateX(-100%);
  transform-origin: top left;
  background-color: #ccc;
  width: 99vh;
  height: 99vw;
}

#container2 {
  transform: rotate(90deg) translateY(-98vh);
  transform-origin: top left;
  white-space: nowrap;
}

.one {
  background-color: #00ff48;
}

.two {
  background-color: #ff00d5;
}

.three {
  background-color: #f00;
}

.back {
  background-color: #fff71c;
}
</style>
</head>

Image8

This creates a horizontally scrolling page divided into several sections with text.

Conclusion

Creating scrolling effects is a straightforward process. With just CSS properties, you can implement unique transitions between sections of a website during scrolling.

The code may be lengthy in some cases, such as multi-layered scrolling where each section moves at a different speed. However, this is still simpler and more efficient than using JavaScript for similar effects.

Check out our reliable and high-performance WordPress hosting solutions for your websites. 

CSS HTML
20.01.2025
Reading time: 8 min

Similar

CSS

How to Create a Sticky Footer Using CSS

You can create many different effects for a website with HTML and CSS. One of the simplest examples is fixing an element in any part of the page during scrolling. In this article, we will explain what a footer is and how to fix it without JavaScript. We will also look at HTML footer examples. What is a Footer? A footer is an element located at the bottom of a website. Sometimes, this element is fixed on the page so that it remains visible during scrolling. The effect is similar to, for example, the chat box on the hostman.com website. When scrolling, it always stays in place. Next, let’s look at a few clear examples of how to make an HTML footer stick on a page. Example 1 We will create a simple site footer as a colored block with a single word. Step 1. Write HTML code with a large number of paragraphs to demonstrate the fixed element during scrolling: <html> <head> <style> </style> </head> <body> <h1>A simple example of a sticky footer</h1> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <p>This text is additional</p> <div class="footer"> <p>Footer</p> </div> </body> </html> Step 2. Using CSS, we will select the font for the text on the page, set the background color, and configure the element's positioning: <style> body { font-family: PT Astra Sans; background-color: #e9e9f0; } .footer { background-color: #2e34e5; position: fixed; right: 0; bottom: 0; text-align: center; width: 99%; font-size: 19px; font-weight: bold; color: #fafaff; } </style> As a result, we’ll have a blue footer on the site that always stays at the bottom during scrolling. This text-containing element will span the full width of the window. Example 2 How can you create a site footer with links to external resources? We'll explain this in the second example: the links will point to images from a free stock photo site. Step 1. Add links to three different images so that we can include them in the HTML footer: <html> <head> <style> </style> </head> <body> <h2>An example of a sticky footer with links to images</h2> <div class="wrapper"> <div class="footer"> <p class="text"> <a href="https://images.unsplash.com/photo-1483728642387-6c3bdd6c93e5?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=876&q=80" class="menu">Pic1</a> <a href="https://images.unsplash.com/photo-1570092178365-4cd46034bb19?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1032&q=80" class="menu">Pic2</a> <a href="https://images.unsplash.com/photo-1604231751678-3f2b03928c10?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=774&q=80" class="menu">Pic3</a> </p> </div> </div> </body> </html> Step 2. Using CSS, we will configure the site dimensions and the footer with three links: .wrapper { height: 1111px; } .footer { background-color: #aac5fa; position:fixed; right:0; bottom:0; width:99%; height: 101px; } .text { float:none; font-size:29px; word-spacing:40px; padding-left:29px; } </style> Step 3. Let’s make it so that the text size and background color change when hovering over the links. <style> a:active { text-decoration: none; } a:link { text-decoration: none; } a.menu:hover { font-size:29px; background-color:#8eff8c; } </style> Example 3 Now let’s look at how to create an HTML site footer with image links to two popular websites. We won't need the <footer> tag. Step 1. Write the code with a large paragraph, add icons for Facebook and Twitter, and include links to their websites. <html> <head> <style></style> </head> <body> <div id="wrapper"> This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. This text is simply included to show how the footer will move during scrolling. </div> <div id="footer"> <div class="all-symbols"> <a href="https://facebook.com/"><img src="https://cdn-icons-png.flaticon.com/256/20/20837.png" class="symbol" alt="FB icon"></a> <a href="https://x.com/"><img src="https://cdn-icons-png.flaticon.com/256/5969/5969020.png" class="symbol" alt="TW icon"></a> </div> </div> </body> </html> Step 2. Use CSS to stick the footer at the bottom of the page and configure the colors and other parameters. The page background will be gray, and the background of the element with icons will be blue. <style> #wrapper { margin: 344 auto 433px; width: 399px; } body { background-color: e2e1eb; } #footer { background-color: #301fed; position: fixed; left: 0; bottom: 0; height: 70px; padding-left: 29px; color: #f3f2ff; width: 99%; } .all-symbols { float:left; margin-top:19px; padding-left:199px; } .symbol { color: #fffcfc; margin-top:6px; margin-left:29px; height:29px; } </style> Step 3. Now make it so that the background color turns white when hovering over the icons: <style> .symbol:hover { padding:2px; background-color:#fffcfc; } </style> As a result, we will have a page where the footer contains Facebook and Twitter icons that link to their respective sites. Example 4 Let’s now look at how to make an HTML footer stick at the bottom of the page with an unusual effect. The block will be hidden beneath the page; to reveal it, users must interact with another element. In this case, that element will be a red dashed square. Step 1. Add many paragraphs to the HTML code. This makes it easier to test the footer's fixation on the page: <style> </style> <h1>To find the footer, hover your cursor over the red square.</h1> <h2><p><p>A simple paragraph is for example here.</p><p>A simple paragraph is for example here.</p><p>A simple paragraph is for example here.</p><p>A simple paragraph is for example here.</p><p>A simple paragraph is for example here.</p><p>A simple paragraph is for example here.</p><p>A simple paragraph is for example here.</p><p>A simple paragraph is for example here.</p><p>A simple paragraph is for example here.</p><p>A simple paragraph is for example here.</p><p>A simple paragraph is for example here.</p><p>A simple paragraph is for example here.</p></p></h2> <div class="wrapper"> <div class="footer"> <div id="button"></div> <div id="block"> <div id="text"> <div class="footer1"> <h1>Hidden footer</h1> </div> </div> </div> </div> Step 2. Next, add the following CSS code to define the background, footer, and other parameters. We’ll use the PT Astra Sans font; the background will be light blue. <style> .wrapper { height: 1111px; } body{ background-color:#8f85ff; font-family: PT Astra Sans; text-align:center; color:#e8e6fc; } .footer #block{ position:relative; margin-top:2px; width:99,99%; height:99%; background: #120f2b; } .footer #text{ Position: relative; right:201px; width:123px; margin:14 auto; top:-51px; } .footer1{ float:left; width:499px; } .footer h1{ color: #ffc9c9; font-family: PT Astra Sans; margin-top:69px; margin-left:39px; } </style> Step 3. Create the red square, which will reveal the hidden block. Using the dashed value, make the object dashed to make it stand out even more. <style> … .footer #button{ width:50px; height:50px; border: #d41542 8px dashed; margin:-3 auto; position:center; } .footer #button:hover{ width:50px; height:50px; border: #d41542 8px dashed; } .footer { position: fixed; right:0; bottom:0; width: 99%; height: 2em; overflow:hidden; transition: all 2s ease; } .footer:hover { transition: all 2s ease; height: 9em; } … </style> The result will be a page where the hidden CSS footer smoothly appears and disappears at any scrolling point. We can apply this effect to any part of the page. The footer only appears when the cursor hovers over the bottom of the window. Conclusion We reviewed four ways to stick an HTML footer on a site. The following CSS properties and values were particularly useful: position: fixed; right: 0; bottom: 0; Instead of text and links, you can include a site search form or a request for clients to leave their contact information in the footer. However, large blocks like these may interfere with page viewing. In such cases, the method in Example 4 can be helpful: creating a small element to hide the HTML footer. Check out our reliable and high-performance WordPress hosting solutions for your websites.
20 January 2025 · 9 min to read
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 Create a Draggable Element

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: Determine what and where we are dragging (draggable element and dropzone). 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. Dragstart: This event is triggered when the dragging of the element begins as soon as the mouse presses down on the element. Dragenter: This event is triggered when the dragged element enters the target area (object). Dragover: The Dragover event occurs when the dragged element is within the target object's area but has not yet been released. Dragleave: This event occurs when the dragged element leaves the target object while the mouse button is still held down. Drag: This event is triggered throughout the entire duration of the dragging process. Drop: If this event is triggered, the dragged element has been "dropped" when the mouse button is released. 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.
15 January 2025 · 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