Home > Software engineering >  how to move elements around web page using jQuery?
how to move elements around web page using jQuery?

Time:12-22

I've created three shapes(circles) on my webpage that are positioned in the background of other elements on the page using z-index in CSS and the position is absolute.

I'm trying to move them around my page as soon as my page loads.

The following is the code I wrote attempting to do the above. I'm not sure what I'm getting wrong. Assistance will be greatly appreciated.

$(function() {
  $("shape-1").animate({
    "margin-top": " = 200px"
  }, 2000);
  $("shape-2").animate({
    "margin-right": " = 200px"
  }, 2000);
  $("shape-3").animate({
    "margin-bottom": " = 200px"
  }, 2000);
});
.shape-1,
.shape-2,
.shape-3 {
  position: absolute;
  border-radius: 50%;
  background: linear-gradient(to right bottom, rgba(197, 96, 223, 0.904), rgba(255, 255, 255, 0.37));
  z-index: 1;
}

.shape-1 {
  top: 1%;
  left: 13%;
  height: 3rem;
  width: 3rem;
}
.shape-2 {
  top: 21%;
  right: 17%;
  height: 6rem;
  width: 6rem;
}
.shape-3 {
  width: 10rem;
  height: 10rem;
  bottom: 25%;
  left: 40%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
<div ></div>
<div ></div>

CodePudding user response:

  • You need to select the elements with a proper CSS selector. $("shape-1") selects nothing, $(".shape-1") does.
  • You need to animate the properties that determine the position of the element. Animating margin-bottom will do nothing for you. The elements are pinned into place by top, bottom, left, and right. You need to animate those.
  • You need to decide whether you want to use percentages (as your CSS defines) or pixels (as your JS code attempts) to position an element. You can't use both.
  • You need to animate percentages as absolute values, you can't do = 50%. You can animate an element from its original absolute position (e.g. 1%) to a new absolute position (e.g. 50%).

$(function() {
  $(".shape-1").animate({top: "50%", left: "50%"}, 2000);
  $(".shape-2").animate({right: "50%"}, 2000);
  $(".shape-3").animate({bottom: "10%"}, 2000);
});
.shape-1,
.shape-2,
.shape-3 {
  position: absolute;
  border-radius: 50%;
  background: linear-gradient(to right bottom, rgba(197, 96, 223, 0.904), rgba(255, 255, 255, 0.37));
  z-index: 1;
}
.shape-1 {
  top: 1%;
  left: 13%;
  height: 3rem;
  width: 3rem;
}
.shape-2 {
  top: 21%;
  right: 17%;
  height: 6rem;
  width: 6rem;
}
.shape-3 {
  width: 10rem;
  height: 10rem;
  bottom: 25%;
  left: 40%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
<div ></div>
<div ></div>

  • Related