DEV Community

Cover image for How to create Drag & Drop or Browse Feature in Javascript
Ashutosh Tiwari
Ashutosh Tiwari

Posted on • Originally published at incoderweb.blogspot.com

How to create Drag & Drop or Browse Feature in Javascript

Hello friends, today in this blog you will learn how to create drag & drop or browse feature in Javascript. In our previous blog, we saw how to create button with hover effect like microsoft in HTML, CSS, and Javascript. Earlier, I shared many projects related to javascript, you can check if you want, and don't forget to check HTML, CSS, and Javascript projects.

Drag and Drop file upload means you can upload the file by drag & drop. Drag and Drop interfaces permit web applications to drag and drop files on a web page. You may have seen this type of file upload feature on most sites. There are many JavaScript libraries to create this type of drag & drop file upload feature with a few lines of JavaScript codes but today in this blog I’ll create it with pure JavaScript means without using any library.

You may like these:

In this program [Drag & Drop or Browse – File upload Feature], on the webpage, there is a drop area container with some text, icon, and browse file button. When you drag any image file over the drag area, the border of the container also changed to solid, and the text “Drag & Drop to upload file” also changed to “Release to upload file”.

When you release your image file in the drag area, immediately the preview of that image will appear. You can also upload an image by clicking on the browse file button. When you click on the button, there is open a file window and you have to select one image file, after you selected it then it will appear in the drag area.

If you are feeling difficulty understanding what am I trying to say, So you can check the source code or preview it as well.

The preview is available here.

HTML Code

<!DOCTYPE html>
<!-- --------------------- Created By InCoder --------------------- -->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drag or Drop</title>
    <link rel="stylesheet" href="main.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
</head>
<body>
    <div class="dragOrDropContainer">
        <div class="icon"><i class="fa-solid fa-cloud-arrow-up"></i></div>
        <div class="header">Drag & Drop to Upload File</div>
        <span>OR</span><br/>
        <button class="browseFile">Browse File</button>
        <input type="file" id="fileInput" hidden>
    </div>

    <script src="script.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS Code

/* --------------------- Created By InCoder --------------------- */

@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

body{
    display: flex;
    height: 100vh;
    align-items: center;
    justify-content: center;
    background-color: #de5d60;
}

.dragOrDropContainer{
    color: #fff;
    margin: 1.2rem;
    padding: 1.2rem;
    overflow: hidden;
    text-align: center;
    max-height: 18rem;
    border-radius: .4rem;
    border: 3px dashed #fff;
    width: clamp(18rem, 65vw, 25rem);
}

.dragOrDropContainer img {
    width: 100%;
    height: 100%;
}

.dragOrDropContainer .icon {
    font-size: 5rem;
}

.dragOrDropContainer.uploaded {
    padding: 0;
    max-height: 13.5rem;
}

.dragOrDropContainer.drag {
    border: 3px solid #fff;
}

.dragOrDropContainer.drag .icon {
    animation: upload 1s infinite linear alternate;
}

@keyframes upload {
    0%{
        transform: translateY(0rem);
    }
    100%{
        transform: translateY(-1rem);
    }
}

.dragOrDropContainer .browseFile {
    width: 8rem;
    height: 2rem;
    color: #fff;
    cursor: pointer;
    margin-top: .6rem;
    border-radius: .4rem;
    border: 2px solid #fff;
    background-color: transparent;
    transition: all .2s ease-in-out;
}

.dragOrDropContainer .browseFile:hover {
    color: #de5d60;
    background-color: #fff;
}
Enter fullscreen mode Exit fullscreen mode

Javascript Code

// --------------------- Created By InCoder ---------------------

let dragOrDropContainer = document.querySelector('.dragOrDropContainer')
dragBoxText = document.querySelector('.dragOrDropContainer .header')
browseFile = document.querySelector('.browseFile')
fileInput = document.querySelector('#fileInput')

let file

fileInput.addEventListener('change', () => {
    file = fileInput.files[0];
    dragOrDropContainer.classList.add("drag")
    uploadFile()
})

const uploadFile = () => {
    let fileType = file.type;
    dragOrDropContainer.style.cursor = 'progress'
    dragBoxText.innerText = 'Uploading file, Please Wait...'
    let validExt = ["image/jpeg", "image/jpg", "image/png"];
    if (validExt.includes(fileType)) {
        let fileReader = new FileReader()
        fileReader.onload = () => {
            let fileURL = fileReader.result
            dragOrDropContainer.classList.add('uploaded')
            let imageTag = `<img src="${fileURL}" alt="image">`
            dragOrDropContainer.innerHTML = imageTag
            dragOrDropContainer.style.cursor = 'auto'
        }
        fileReader.readAsDataURL(file)
    } else {
        dragOrDropContainer.classList.remove("drag")
        dragBoxText.innerText = "Drag & Drop to Upload File"
        alert("This File is nat valid. Please choose another file and try again.")
    }
}

dragOrDropContainer.addEventListener('dragover', (e) => {
    e.preventDefault()
    dragOrDropContainer.classList.add('drag')
    dragBoxText.innerText = 'Release to Upload File'
})

dragOrDropContainer.addEventListener('dragleave', (e) => {
    dragOrDropContainer.classList.remove('drag')
    dragBoxText.innerText = 'Drag & Drop to Upload File'
})

dragOrDropContainer.addEventListener('drop', (e) => {
    e.preventDefault()
    file = e.dataTransfer.files[0];
    uploadFile()
})

browseFile.addEventListener('click', () => {
    fileInput.click()
})
Enter fullscreen mode Exit fullscreen mode

Discussion (0)