質問

So Im a bit stuck on something I am working on;

I'm brand new into the Jquery and Javascript world and I'm sure there is a much more efficient way to do this, but for now, this is what i have.

Basically when the user clicks on an 'answer' an element will animate on the page. there are 2 answers with matching elements that will animate if the corresponding 'answer' is clicked.

Right now, when the user clicks on one answer multiple times, it continues to animate; I need for when the user clicks on an answer, it animates just once, and stops, so the user either leaves it, or when they click the other' answer', it performs the animation, but becomes re-binded to reclick. sort of like toggling back and forth between the 2 answers/corresponding animations.

I'm having trouble re-binding so it becomes available to click again. sort of in a loop.

Hope Im explaining this ok! Thanks for anyone who can point me in the right direction with this.

Here is the JS, with a FIDDLE below of where Im at.

   /*answer1*/
$('ul#quiz li:nth-child(2)').on("click", function() {
  $(this).addClass('active');
  $(this).siblings().addClass('deactive');
  $(this).siblings().removeClass('active');
  $(this).removeClass('deactive');
  if ($('ul#quiz li:nth-child(3)').hasClass('deactive')) {
      $('.circle2').animate({
          width: "80px",
          height: "80px"
      });
  }
  if ($(this).hasClass('active')) {
      $('.circle1').animate({
          width: "+=3.5%",
          height: "+=3.5%"
      });
  }
 }); 
  /*answer2*/
 $('ul#quiz li:nth-child(3)').on("click", function() {
  $(this).addClass('active');
  $(this).siblings().addClass('deactive');
  $(this).siblings().removeClass('active');
  $(this).removeClass('deactive');
  if ($('ul#quiz li:nth-child(2)').hasClass('deactive')) {
      $('.circle1').animate({
          width: "80px",
          height: "80px"
      });
  }
   if ($(this).hasClass('active')) {
      $('.circle2').animate({
          width: "+=3.5%",
          height: "+=3.5%"
      });
    }
   });       

FIDDLE

役に立ちましたか?

解決

You want to animate only if the answer is not already in the active state. Just wrap everything in your click handlers in

if($(this).hasClass('active') === false) {
}

For an extra credit assignment, move all of your click handler stuff out into a separate function and then call that one function from both click handlers, rather than duplicating all that code in both. Good luck!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top