Moving div in javascript

How can I move a div with direction in JavaScript?

There is a element in HMTL that I would like to move. It is simple. The problem is the element should move in specified degrees, for example 30° deg. How can I do that in JavaScript (and with CSS rotate)? Thanks for all the answers.

vinayakj, I checked it and yes, I mean something like that, but I would like to move the element in direction.

3 Answers 3

If I understand it well, you can use Math.cos and Math.sin to get the horizontal and vertical components of the desired vector, and then increase the top and left properties:

Click somewhere. jsfiddle.net/o9zd5tvp/19/
Or Run snippet below.

Rotate only do rotation «in a place».

You can move only by changing position (left and top).
(each element in HTML is just a block at point x,y)

Don’t forget to set position: absolute in css to make div floatable.

var d = 30; document.getElementById("div1").style.transform = "rotate("+0+"deg)"; var mx,my; $( "body" ).bind( "mousemove", function(event) < mx = event.clientX; my = event.clientY; >); var div = document.getElementById("div1"); $( "BODY" ).bind( "click", function(event) < $('#div1').animate(< left: mx-32, top: my-32, >,300 + Math.random()*600) >); setInterval(function()< var dx = mx - div.offsetLeft-32; var dy = my - div.offsetTop-32; var v1 = , v2 = ; var angleDeg = Math.atan2(v2.y - v1.y, v2.x - v1.x) * 180 / Math.PI ; div.style.transform = "rotate("+angleDeg+"deg)"; div.innerHTML = Number(angleDeg).toFixed(2); >,30);
 Click the mouse somewhere.

Источник

JavaScript How to Dynamically Move Div by Clicking and Dragging

Okay it would seem like it should be simple. I need to take an already existing div and move it according to mouse position within the window. I have searched everywhere and it has led me to over-complicated ways of doing the same thing and involves the use of j-query. I need to strictly use javascript for what I am trying to do. Method :

var mousePosition; var div; (function createDiv()< div = document.createElement("div"); div.style.position = "absolute"; div.style.left = "0px"; div.style.top = "0px"; div.style.width = "100px"; div.style.height = "100px"; div.style.background = "red"; div.style.color = "blue"; div.addEventListener('mousedown', handleKeyPressed, true); document.body.appendChild(div); >)(); function handleKeyPressed(event) < event.preventDefault(); mousePosition = < x : event.clientX, y : event.clientY >; div.style.left = mousePosition.x; div.style.top = mousePosition.y; //alert("whoa!"); > 

@adeneo jQuery is a javascript library want to learn about javascript not jquery although I know it is conventional to use it, not interested in learning it as of now. Just looking into pure javascript.

9 Answers 9

I think you’re looking for something more like this

var mousePosition; var offset = [0,0]; var div; var isDown = false; div = document.createElement("div"); div.style.position = "absolute"; div.style.left = "0px"; div.style.top = "0px"; div.style.width = "100px"; div.style.height = "100px"; div.style.background = "red"; div.style.color = "blue"; document.body.appendChild(div); div.addEventListener('mousedown', function(e) < isDown = true; offset = [ div.offsetLeft - e.clientX, div.offsetTop - e.clientY ]; >, true); document.addEventListener('mouseup', function() < isDown = false; >, true); document.addEventListener('mousemove', function(event) < event.preventDefault(); if (isDown) < mousePosition = < x : event.clientX, y : event.clientY >; div.style.left = (mousePosition.x + offset[0]) + 'px'; div.style.top = (mousePosition.y + offset[1]) + 'px'; > >, true); 

It’s because it’s always at the top left corner of the mouse pointer, you have to calculate the offset of the element in relation to where you clicked, but that’s almost a question in itself.

Читайте также:  Java get base path

@adeneo thanks. 🙂 although you could have simply called me an idiot for forgetting to add px to the end of div.style.left = e.clientX;. But this helped me even more much appreciated.

This is by far the best solution I have ever seen. The script is small and easy to understand and the results work better than anything else I’ve seen on various browsers. I am compelled to comment and vote, if only to find this again in the future.

Support for touch inputs

All other answers (including the accepted one) do not work with touch inputs. Touch inputs have events different than that of mouse inputs. See Using Touch Events on MDN.

The following code snippet works even with touch inputs. I have highlighted all lines of code that need to be added to support touch devices.
The basic idea here is that every element containing draggable in the class list should be draggable. This concept is easier to follow when you have a big number of elements that need to be dragged.

See this Glitch page and following for a demo.

const d = document.getElementsByClassName("draggable"); for (let i = 0; i < d.length; i++) < d[i].style.position = "relative"; >function filter(e) < let target = e.target; if (!target.classList.contains("draggable")) < return; >target.moving = true; //NOTICE THIS 👇 Check if Mouse events exist on users' device if (e.clientX) < target.oldX = e.clientX; // If they exist then use Mouse input target.oldY = e.clientY; >else < target.oldX = e.touches[0].clientX; // Otherwise use touch input target.oldY = e.touches[0].clientY; >//NOTICE THIS 👆 Since there can be multiple touches, you need to mention which touch to look for, we are using the first touch only in this case target.oldLeft = window.getComputedStyle(target).getPropertyValue('left').split('px')[0] * 1; target.oldTop = window.getComputedStyle(target).getPropertyValue('top').split('px')[0] * 1; document.onmousemove = dr; //NOTICE THIS 👇 document.ontouchmove = dr; //NOTICE THIS 👆 function dr(event) < event.preventDefault(); if (!target.moving) < return; >//NOTICE THIS 👇 if (event.clientX) < target.distX = event.clientX - target.oldX; target.distY = event.clientY - target.oldY; >else < target.distX = event.touches[0].clientX - target.oldX; target.distY = event.touches[0].clientY - target.oldY; >//NOTICE THIS 👆 target.style.left = target.oldLeft + target.distX + "px"; target.style.top = target.oldTop + target.distY + "px"; > function endDrag() < target.moving = false; >target.onmouseup = endDrag; //NOTICE THIS 👇 target.ontouchend = endDrag; //NOTICE THIS 👆 > document.onmousedown = filter; //NOTICE THIS 👇 document.ontouchstart = filter; //NOTICE THIS 👆

Источник

Moving div in javascript

  • Difference between HTML and CSS
  • What are physical tags in HTML?
  • HTML | Deprecated Tags
  • Container and Empty Tags in HTML
  • HTML Comments
  • How to set background image in HTML ?
  • How to define a list item in HTML5?
  • Difference between semantic and non-semantic elements
  • How to Create Color Picker input box in HTML ?
  • HTML Hex Color Codes
  • HTML Block and Inline Elements
  • HTML Drag and Drop
  • How to set the name for the object in HTML5?
  • How to add space between elements ?
  • How to create a clickable button in HTML ?
  • HTML Links
  • How to link back out of a folder using the a-href tag?
  • HTML ping Attribute
  • HTML disabled attribute
  • What is the use of “#” symbol in link URL ?
  • How to create a link with a media attribute in HTML5 ?
  • How to specify the source URL of the quote using HTML5 ?
  • How to specify that the target will be downloaded when a user clicks on the hyperlink in HTML5 ?
  • How to specify the hyperlink target for the area of an image in HTML5 ?
  • How to make a HTML link that forces refresh ?
  • How to set the language of text in the linked document in HTML5 ?
  • How to specify what media/device the target URL is optimized for ?
  • How to specify URL of resource to be used by the object in HTML5 ?
  • How to use Anchor tag as submit button ?
  • Elements of a form Tag
  • How to set an alternate text for area in HTML5 ?
  • How to specify one or more forms the object belongs to ?
  • How to specify one or more forms the keygen element belongs to ?
  • How to turn on/off form autocompletion in HTML ?
  • How to specify that a group of related form elements should be disabled using HTML?
  • How to specify how form-data should be encoded when submitting to server ?
  • How to specify the URL that will process the data supplied through input(s) when the form is submitted?
  • How to specify one or more forms the label belongs to ?
  • How to specify multiple forms the select field belongs to in HTML ?
  • How to change the type?
  • How to specify which form element a label is bound to ?
  • How to create a multiline input control text area in HTML5 ?
  • How to create form validation by using only HTML ?
  • HTML Emojis
  • How to animate a straight line in linear motion using CSS ?
  • How to specify the media type of the script in HTML5 ?
  • How to display video controls in HTML5 ?
  • How to mute video using HTML5 ?
  • How to add controls to an audio in HTML5 ?
  • Create Scanning Animation Loader using HTML & CSS
  • How to specify media type of data specified in data attribute in HTML5 ?
  • How to set the height and width of the video player in HTML5 ?
  • How to check whether an image is loaded or not ?
  • How to specify the type of the media resource in HTML5 ?
  • How to Create Image Hovered Detail using HTML & CSS ?
  • How to define media type of style tag in HTML5 ?
  • How to set multiple media resources for elements in HTML5 ?
  • How to set a single line break in HTML5 ?
  • How to create a progress bar using HTML and CSS?
  • How to create Perspective Text using HTML & CSS ?
  • How to isolate a part of text that may be formatted in a different direction using HTML5 ?
  • Design an Event Webpage using HTML & CSS
  • How to Skew Text on Hover using HTML and CSS?
  • Programming a slideshow with HTML and CSS
  • How to specify that an option-group should be disabled in HTML5 ?
  • How to disable the drop-down list in HTML5 ?
  • How to define scalar measurement within a given range in HTML5 ?
  • How to set the security algorithm of key in HTML5 ?
  • How to set minimum and maximum value of range in HTML5 ?
Читайте также:  Решение определенного интеграла питон

Источник

Moving Div Box using javascript

I am trying to create a 300px by 300 px div box that moves a few pixels when the user has their mouse on the box. The only thing is when the div hits the end of the browser size I want it to to start moving the other way and not make the window scroll. Any help would be greatly appreciated.

5 Answers 5

Start by creating a couple of variable that keep track of speed and direction:

var speed = 10, // the box will move by 10 pixels on every step direction = 1; // 1 moves in the positive direction; -1 vice versa 

Then grab a reference to your box and attach an event handler to its «mouseover» event:

var boxElement = document.getElementById('theIdOfTheBox'); if (boxElement) < boxElement.addEventListener('mouseover', function () < // Calculate and store some of the box coordinates: var boxLeftPos = boxElement.offsetLeft, boxRightPos = boxLeftPos + boxElement.offsetWidth; // When right side of the box goes too far - change direction: if (boxRightPos >document.body.offsetWidth) < direction = -1; >// When left side of the box goes too far - change direction: if (boxLeftPos < 0) < direction = 1; >// Recalculate position: boxElement.style.left = (boxLeftPos + speed * direction) + 'px'; >); > 

All done, here’s a jsfiddle for you to play around with.

Mind, however, the position: absolute; in the CSS and the fact that you need to wait for the DOM to load to be able to safely perform the getElementById operation.

If you want to avoid usage of offsets, you may want to parse and manipulate margins or padding of the box instead.

If you want to animate the movement of your box, you can try CSS animations. Just add the following to the style declaration of your box in the CSS:

-webkit-transition: left 0.3s 0.1s ease-out; 

The above code will animate any changes in left property in webkit browsers. You can add other vendor prefixes (and none for compatibility with future releases) to enable animation in other browsers that support it.

Читайте также:  Get current directory kotlin

EDIT

Regarding your comment with running the script on browser launch:

First of all make sure to wrap the JavaScript code in tags if you are embedding it in an HTML page. You can run a validator (e.g. validator.w3.org) to ensure you have a correct document structure.

Secondly, place the code inside those tags as close as possible to the end of the body of your document, i.e. .

You can also wrap the entire JavaScript code in a function that will be executed once the document is fully loaded. This way the code can be placed (or remotely required) from the document head (but why would you want that?). Here’s how it’s done:

window.addEventListener('load', function () < // . the code goes here >); 

A (non-recommended) alternative is:

Or (please avoid this, it’s just an example) in HTML:

So, the resulting code might look like:

      
I'm a box.

Special note regarding Internet Explorer

There’s no support for addEventListener in Internet Explorer below version 9. You should use attachEvent instead.

Источник

Оцените статью