Looking for a drag-and-drop solution using Vanilla Javascript, no need for jQuery

Looking for assistance with creating a click-and-drag solution for a background image using Vanilla Javascript. I came across a jQuery solution on Codepen, but I need help translating it into Vanilla Javascript.

    Draggable.create(".box", {
        bounds:$container,
        edgeResistance:0.65,
        type:"x,y",
        throwProps:true,
        autoScroll:true,
    });

Check out the Codepen solution here.

The final project will be in Vue, but for now, plain HTML, CSS, and Javascript will do the trick.

Answer №1

This method may not be as slick as using jquery draggable, but it gets the job done.

<!DOCTYPE html>
<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>Document</title>
    <style>
      body,
      html {
        height: 100%;
        width: 100%;
      }

      body {
        background-color: black;
      }

      #container {
        background-color: #333;
        height: 100%;
        width: 100%;
        overflow: hidden;
        position: relative;
      }

      #box {
        background-image: url(http://www.vgmaps.com/NewsArchives/April2005/LegendOfZelda-Link%27sAwakeningAdvance-Koholint.png);
        background-size: 100%;
        background-position: center;
        width: 100%;
        height: 100%;
        position: absolute;
      }

      #box:hover {
          cursor: move;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <div id="box"></div>
    </div>
  </body>
  <script>
    dragElement(document.getElementById("container"));

    function dragElement(elmnt) {
      var pos1 = 0,
        pos2 = 0,
        pos3 = 0,
        pos4 = 0;
      if (document.getElementById("box")) {
        /* if present, the header is where you move the DIV from:*/
        document.getElementById("box").onmousedown =
          dragMouseDown;
      } else {
        /* otherwise, move the DIV from anywhere inside the DIV:*/
        elmnt.onmousedown = dragMouseDown;
      }

      function dragMouseDown(e) {
        e = e || window.event;
        e.preventDefault();
        // get the mouse cursor position at startup:
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        // call a function whenever the cursor moves:
        document.onmousemove = elementDrag;
      }

      function elementDrag(e) {
        e = e || window.event;
        e.preventDefault();
        // calculate the new cursor position:
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;
        // set the element's new position:
        elmnt.style.top = elmnt.offsetTop - pos2 + "px";
        elmnt.style.left = elmnt.offsetLeft - pos1 + "px";
      }

      function closeDragElement() {
        /* stop moving when mouse button is released:*/
        document.onmouseup = null;
        document.onmousemove = null;
      }
    }
  </script>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize styled-components in next.js to import and resize .svg files seamlessly

I have been attempting to import .svg files into my next.js project, but I have not had any success. I tried importing the .svg files the same way as in my React project by creating a typing.d.ts file and importing the svg as a component. However, it did ...

Ways to stop a JavaScript function from running during page loading

After clicking the submit button on my form, I want to send a confirmation post using the sendPostAjax() function before submitting the form to the payment provider. However, I'm facing an issue where the sendPostAjax() function is getting executed as ...

Encountered a glitch during the npm installation process for mui core

I recently set up a new create-react-app and am still encountering the same error message. After installing MUI, I'm getting an 'unable to resolve dependency tree' issue. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve depende ...

Is it not feasible to place a well within a column using Bootstrap?

Would like to place a .well div (or a button, whichever works best) within the designated green area shown in this image: here Here is the code I currently have: <div class="container-fluid"> <div class="row row1" style=&q ...

What is the best way to compare all the elements in an array to the entries in another object, while also storing the results of each comparison?

I am working with a JSON file that contains an array of 2 objects: `{ bg: 'a', o: 'c' }`, `{hg': 'a2', 'oo': 'c3'}`. My goal is to compare each object in the array with another object structured as fol ...

Trouble retrieving desired data from an array of objects in React Native

I'm having trouble retrieving values from an array of objects in my state. When I try to access the values, it only prints out "[Object Object]". However, when I stored the values in a separate array and used console.log, I was able to see them. Here ...

Issue encountered in AngularJS while configuring resources for the action `query`: Anticipated response was an object, but received an array instead

I've been attempting to utilize Angular 1.3 to access a REST service, but I keep encountering an error stating "Error: error:badcfg Response does not match configured parameter". My suspicion lies in the controller where I invoke $scope.data. Even th ...

Replace the JS function in the bundle with a new custom function

I have compiled my AngularJS website using webpack. While in the Chrome console, I am trying to override a function within the controller of a particular directive. Is this achievable? ...

A step-by-step guide on utilizing img src to navigate and upload images

I would like to hide the input type='file' element with id "imgInp" that accepts image files from users. Instead, I want them to use an img tag to select images when they click on a specific img tag. How can this be achieved using jQuery? Here i ...

When decoding a JWT, it may return the value of "[object Object]"

Having some trouble decoding a JSON web token that's being sent to my REST API server. I can't seem to access the _id property within the web token. Below is the code I'm currently using: jwt.verify(token, process.env.TOKEN_SECRET, { comp ...

remove a specific element from an array

Hey there! I'm attempting to remove only the keys from an array. Here's the initial array: {everyone: "everyone", random: "random", fast response time: "fast response time", less conversations: "less conversatio ...

Transferring information to a function

I'm looking for a way to pass the variable Date to my function HasBtnRights(). Does anyone have suggestions on how I can achieve this? <asp:TemplateField HeaderText="More info" Visible='<%#HasBtnRights(Eval("Date")) %>'> < ...

Creating an editable list item with jQuery: A step-by-step guide

I am trying to create a user-friendly interface where users can view and edit their information in a listview. The data will be retrieved from a database and displayed in the listview. My goal is to make the listview editable, so when a user clicks on it ...

Why won't the value in jQuery attr() be updated?

Just joined this platform for the first time and can't seem to find a similar issue posted before.. :( I'm currently trying to catch up with jQuery and JavaScript. My problem is that I want to dynamically change the href attribute of an anchor e ...

What could be the reason for my component not getting the asynchronous data?

Currently, I am delving into the intricacies of React and have been following a tutorial that covers creating components, passing props, setting state, and querying an API using useEffect(). Feeling confident in my understanding up to this point, I decided ...

The command is not currently carrying out its function

I am attempting to verify whether the "sender" has either of the two specified roles, but for some reason the command is not being executed. There are no errors showing up in the console, it's just that the command doesn't run. const revAmount = ...

Tips for configuring Webstorm to automatically change double quotes to single quotes when reformatting source code

After using cmd + alt + l in Webstorm to format my JavaScript code, I noticed that double quotes are used instead of single quotes. How can I configure Webstorm to automatically change the double quotes to single quotes in my code? ...

vue implementing vuelidate for obligatory server fields

After retrieving the list of required fields from the server, I aim to transfer this list into the validations function. data() { return { fieldsFromServer: {}, requiredFields: {}, } }, created() { dataAPI.getFormData() .then(r ...

Select the first item that is visible and chosen

Currently, I am working with a select list: <option ng-repeat="hour in Hours" value="{{hour.Value}}" ng-show="filterEvent($index)" ng-selected="hour.Value == EventDate || $first"> {{hour.Text}} </opti ...

Can you provide a list of factors that influence coverage? Additionally, is there a specific algorithm available for calculating

As part of my Angular project, I am currently focusing on writing unit test cases using the Jasmine Framework and Karma. To ensure thorough testing coverage, I am utilizing Coverage-html (Istanbul). When it comes to coverage, there are several important t ...