0

I'm making this little exemple where I'm trying to center an image to the cursor, basically, when you click, the cursor should be at the center of the image. Since I'm a beginner, I don't really see how I could achieve that. Maybe it's by using something like $(".theImg").height but I think I'm doing this wrong since it doesn't work. Maybe I have to use a transform...

$(document.body).click(function(event) {
        x = event.pageX;
        y = event.pageY;
        console.log(x +", "+ y);
        console.log(('theImg').height);

        $(".paysage") .css({'position' : 'absolute', 'top': y, 'left' : x})
                      .prepend($('<img>',{  class:'theImg',
                                            src:'https://www.30millionsdamis.fr/uploads/pics/conseils-erreurs-chat-1171.jpg'})) 
        $(".theImg").prev().remove();       
              
});
body{
  width: 100vw;
  height: 100vh
}

.theImg{
  width :20em;
  height: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "paysage"> </div>
Aurore
  • 696
  • 4
  • 16

2 Answers2

2

Using transform css property on img

transform: translate(-50%, -50%)

$(document.body).click(function(event) {
  x = event.pageX;
  y = event.pageY;
  console.log(x + ", " + y);
  console.log(('theImg').height);

  $(".paysage").css({
      'position': 'absolute',
      'top': y,
      'left': x
    })
    .prepend($('<img>', {
      class: 'theImg',
      src: 'https://www.30millionsdamis.fr/uploads/pics/conseils-erreurs-chat-1171.jpg'
    }))

  $(".theImg").prev().remove();
});
body {
  width: 100vw;
  height: 100vh
}

.theImg {
  width: 20em;
  height: auto;
  transform: translate(-50%, -50%)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="paysage"></div>
User863
  • 19,346
  • 2
  • 17
  • 41
1

Add this selector with rule to your css:

.paysage {
  transform: translate(-50%, -50%);
}

Was it necessary?

$(document.body).click(function(event) {
        x = event.pageX;
        y = event.pageY;
        console.log(x +", "+ y);
        console.log(('theImg').height);

        $(".paysage") .css({'position' : 'absolute', 'top': y, 'left' : x})
                      .prepend($('<img>',{  class:'theImg',
                                            src:'https://www.30millionsdamis.fr/uploads/pics/conseils-erreurs-chat-1171.jpg'})) 
        $(".theImg").prev().remove();       
              
});
body{
  width: 100vw;
  height: 100vh
}

.theImg{
  width :20em;
  height: auto;
}

.paysage {
  transform: translate(-50%, -50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "paysage"> </div>
s.kuznetsov
  • 14,870
  • 3
  • 10
  • 25