Change margin-left according to the coordinates where you clicked

4

I want that when I click on the screen I take the coordinates and those coordinates are placed as a value for the margin-left. This is my javascript code.

function coordenadas(event) {
 x=event.clientX;
 y=event.clientY;
 document.getElementById("#img").style.marginLeft=x;
 alert("X: "+x+"px Y: "+y);

}
    
asked by Borja Sanchez 30.03.2017 в 16:51
source

4 answers

3

I think this is what you want

var cat = document.getElementById('img');

function showCoords(event) {
  cat.style.marginLeft = event.clientX + 'px';
}
.container {
  width: auto;
  height: auto;
  border: 1px solid black;
  padding: 5px 0px 0px 5px;
}

#img {
  width: 100px;
}
<div class="container" onclick="showCoords(event)">
  <img id="img" src="https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg" />
</div>
    
answered by 30.03.2017 в 17:09
2

You could do the following:

  • Absolutely position the image ( eg: position: absolute ).
  • Subscribe to the event click of document to get the coordinates
  • Set margin-left to coord X

Example:

var img = document.getElementById('image');
document.addEventListener('click', function(evt) {
  // Coord X - Margen izq
  img.style.marginLeft = evt.clientX + 'px';
  // Coord Y - Margen top y sumamos la mitad de la altura de la imagen
  img.style.marginTop = evt.clientY + (img.offsetHeight / 2) + 'px';
});
* {
  margin: 0;
  padding: 0;
}
#image {
  position: absolute;
  width: 25px;
  top: -25px;
}
<img id="image" src="https://image.flaticon.com/icons/svg/17/17264.svg" />
    
answered by 30.03.2017 в 17:11
2

Here you have to move with the click.

Change the div for your image.

Pick up the mouse position with the click event and assign it to the style of the element, image in your case.

var mouseX = 0, 
    follower = document.getElementById("follower");


document.onclick = function(e){
   mouseX = e.pageX;

   follower.style.marginLeft = mouseX + 'px';
};
#follower{
  position : absolute;
  background-color : red;
  color : white;
  padding : 10px;
}

body{width:100%;height:100%;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="follower">Imagen</div>
    
answered by 30.03.2017 в 17:12
2

Well it seems to me that what you have is enough, I add what it takes to make it look functional. Just add the event listener and adjust the margin left in pixels with the desired value.

(function(window){
  window.addEventListener('click', function( event ) {
    var x=event.clientX,
        y=event.clientY;
        img = document.getElementById("img").style.marginLeft=x + "px";
  });  

})(window);
img{
  width: 150px;
  height: 100px;
}
<img id="img" src="https://assets.entrepreneur.com/content/16x9/822/20141230193127-work.jpeg" alt="dev">
    
answered by 30.03.2017 в 17:15