Anthony Honciano
Anthony Honciano

Reputation: 1677

Center div based on click coords

I tried searching this, but most of the answers I'm seeing is just to center something in a div. What I'm looking to do is click somewhere on an image and center that area that I clicked.

I have a viewport div and an image div inside "viewport. (overflow:hidden). I was able to write something where it seems to work the first time, but when I click the second time, it doesn't get it right unless I refresh.

HTML:

<div id="viewport">
    <div id="garage-layout"></div>
</div>

JavaScript:

$("#garage-layout").click(function (e) {
    posX = e.pageX - $(this).offset().left;
    posY = e.pageY - $(this).offset().top;

    vP = $("#viewport");
    vX = e.pageX - vP.offset().left;
    vY = e.pageY - vP.offset().top;
    vW = (vP.width() / 2) - vX;
    vH = (vP.height() / 2) - vY;

    console.log("vy:" + vY + " vx:" + vX + " vW:" + vW + "vH" + vH);
    $(this).animate({
        top: vH,
        left: vW
    }, 1500);
})

Here's what I got: http://jsfiddle.net/86j20Lsb/1/

Much appreciated!!

Upvotes: 0

Views: 171

Answers (2)

Koti Panga
Koti Panga

Reputation: 3720

Here is Solution Working Fiddle:
Below are JS, CSS, HTML are below

$(document).on("click", "#garage-layout", function (e) {
    var v = $("#viewport"),
        p = v.offset(),
        el = $(this);
    $(this).animate({
        /*To postion el in viewport center*/
        top: p.top - parseInt(v.css("marginTop"), 10) + Math.abs((v.height() - el.height()) / 2),
        left: p.left - parseInt(v.css("marginLeft"), 10) + Math.abs((v.width() - el.width())) / 2

        /*To place el center to cursor position.*/
        //top: e.pageY - p.top - el.height() / 2,
        //left: e.pageX - p.left - el.width() / 2
    }, 400);
});
#garage-layout {
  position: relative;
  width: 200px;
  height: 150px;
  background: url(http://www.freephotosbank.com/photographers/photos1/29/med_ap104s3823.jpg);
  background-repeat: repeat;
}
#viewport {
  position: relative;
  width: 300px;
  height: 200px;
  margin: 0 auto;
  border: 5px solid green;
  margin-top: 10px;
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="viewport">
  <div id="garage-layout"></div>
</div>

Upvotes: 1

Anthony Honciano
Anthony Honciano

Reputation: 1677

I was subtracting the wrong variable.

vW = (vP.width()/2) -  posX;
vH = (vP.height()/2) - posY;

http://jsfiddle.net/86j20Lsb/4/

Thank, y'all!

Upvotes: 0

Related Questions