How to animate position absolute from right to left and then left to right in jQuery?

Viewed 68

I am trying to make a simple game in which a boat goes from one shore to another shore when GO button is clicked. I tried to use jQuery animate but it didn't worked as expected.

Pug

body
  button.go GO
  .main 
    .left 
      .seaShore
    .travel 
      .boat
      .river 
    .right 
      .seaShore

Sass

*
    margin: 0
    padding: 0
    box-sizing: border-box

@mixin flex($justify,$align)
    display: flex
    justify-content: $justify
    align-items: $align

.go
    padding: 5px 10px
    position: fixed
    top: 20px
    right: 50%
    transform: translateX(50%)

.main
    height: 100vh
    @include flex(center,flex-end)

.seaShore
    background-color: green
    width: 25vw
    height: 300px

.travel
    position: relative
    .boat
      position: absolute
      top: -15px
      right: 0
      width: 200px
      height: 40px
      border-radius: 0 0 50% 50%
      background-color: brown

    .river
        width: 50vw
        height: 290px
        background-color: #00bfff

jQuery

$(document).ready(function () {
  let right = false;
  let offset = $('.boat').offset();
  $(".go").click(function () {
    !right
      ? $(".boat").animate(
          {
            left: "0",
            right: offset.left - 200
          },
          "veryfast"
        )
      : $(".boat").animate(
          {
            left: offset.left - 100,
            right: 0
          },
          "veryfast"
        );

    right = !right;
  });
});

The problem is when the boat is coming back to the starting position then it is going a bit further than the original position.

Can any one please help me?

CODE PEN LINK

2 Answers

Instead of using $('.boat').offset() use document.querySelector('.boat').offsetLeft it will fix your problem and it will also be dynamic.

$(document).ready(function () {
    let right = false,
        offset = document.querySelector('.boat').offsetLeft;
    $('.go').click(function () {
        !right
            ? $('.boat').animate({ left: '0', right: offset }, 'veryfast')
            : $('.boat').animate({ left: offset, right: 0 }, 'veryfast');
        right = !right;
    });
});

Are you looking for a dynamic solution ? If not then you can just modify the value to subtract

e.g change

left: offset.left - 100,

to become

left: offset.left - 382,

And you can just play around with the number -382 to ensure it fits nicely

Related