Jump to content

Draggable Image

Recommended Posts

Hi! 

I have a client hoping to make an image draggable (just one image). I've found a codepen code, but I'm not sure how to put the codepen into my site correctly (there seems to be different options). If someone could help me figure out how to do that with my tester site (we can use the oval image on the second section, code block: #block-374ede71b52e85ca10b8) Thank you!!

site: https://krill-cinnamon-fcfj.squarespace.com/
password: hello

 

Link to comment
  • Replies 1
  • Views 610
  • Created
  • Last Reply

Top Posters In This Topic

Popular Days

Top Posters In This Topic

Add a Code Block > paste this code

<div id="draggable" class="dragme">"Hello World!"</div>
<img src="https://lh4.googleusercontent.com/-8tqTFxi2ebU/Ufo4j_thf7I/AAAAAAAADFM/_ZBQctm9e8E/w270-h203-no/flower.jpg" alt="drag-and-drop image script" 
 title="drag-and-drop image script" class="dragme">
<style>
  .dragme {
  position: relative;
  width: 270px;
  height: 203px;
  cursor: move;
}

#draggable {
  background-color: #ccc;
  border: 1px solid #000;
}
</style>
<script>
  	function startDrag(e) {
				// determine event object
				if (!e) {
					var e = window.event;
				}
                if(e.preventDefault) e.preventDefault();

				// IE uses srcElement, others use target
				var targ = e.target ? e.target : e.srcElement;

				if (targ.className != 'dragme') {return};
				// calculate event X, Y coordinates
					offsetX = e.clientX;
					offsetY = e.clientY;

				// assign default values for top and left properties
				if(!targ.style.left) { targ.style.left='0px'};
				if (!targ.style.top) { targ.style.top='0px'};

				// calculate integer values for top and left 
				// properties
				coordX = parseInt(targ.style.left);
				coordY = parseInt(targ.style.top);
				drag = true;

				// move div element
					document.onmousemove=dragDiv;
                return false;
				
			}
			function dragDiv(e) {
				if (!drag) {return};
				if (!e) { var e= window.event};
				var targ=e.target?e.target:e.srcElement;
				// move div element
				targ.style.left=coordX+e.clientX-offsetX+'px';
				targ.style.top=coordY+e.clientY-offsetY+'px';
				return false;
			}
			function stopDrag() {
				drag=false;
			}
			window.onload = function() {
				document.onmousedown = startDrag;
				document.onmouseup = stopDrag;
			}
</script>

 

Email me if you have need any help (free, of course.). Answer within 24 hours. 
Or send to forum message

Contact Customer Care - Learn CSS - Buy me a coffee (thank you!)

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment


×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.