Skip to content

jQuery: Get middle point of box, place object above on button click

I would need the following:

  • On button click, the red circle should center in the middle of the text box.
  • It should be based on the pixel position of the screen. (No nesting with flexbox or something like that.)
  • It should work responsive.

Here is my approach:

$("button").click(function() {
  $("#circle").css("left", middle_point_of_box);
  $("#circle").css("right", middle_point_of_box);
});
#text {
  background-color: lightgray;
  width: 40%;
}

#circle {
  width: 20vw;
  height: 20vw;
  background-color: red;
  border-radius: 50%;
  position: absolute;
  top: 0; /* Middle Point of Text Box */
  left: 0; /* Middle Point of Text Box */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
  sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
  Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>

<div id="circle"></div>

<button>Click me</button>

How is it possible to code that? I would be very thankful for help!

Answer

Just use a combination of jQuery’s offset() and width()

let targetCenter = {
  x: $('#text').offset().left + $('#text').width() / 2 - $('#circle').width() / 2,
  y: $('#text').offset().top + $('#text').height() / 2 - $('#circle').height() / 2
}

$("button").click(function(e) {
  $("#circle").css("left", targetCenter.x + 'px');
  $("#circle").css("top", targetCenter.y + 'px');
});
#text {
  background-color: lightgray;
  width: 40%;
}

#circle {
  width: 20vw;
  height: 20vw;
  background-color: red;
  border-radius: 50%;
  position: absolute;
  top: 0;
  /* Middle Point of Text Box */
  left: 0;
  /* Middle Point of Text Box */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
  sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
  Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>

<div id="circle"></div>

<button>Click me</button>