1

I have this script that on click fades an element, changes css and unfades it. I want that on the second click it would do the same but change to some other css. I want it to do this in a some kind of loop. And also can I make this in less code? Sorry if it's an easy question, I'm new at js.

<script>
  $(function() {
  $("#banner").click(function() {
  $("#banner").fadeOut("fast", function() {
  $("#banner").css({top:"0", left:"0"});
  }).fadeIn("slow");
  });
  });
</script>

1 Answer 1

1

You need some sort of indicator that the script has already run. You can do this by adding a class name and checking for it.

$(function() {
  $("#banner").click(function() {
      if($("#banner").hasClass('done')) {
          // your new code
      }
      $("#banner").addClass('done');
      $("#banner").fadeOut("fast", function() {
        $("#banner").css({top:"0", left:"0"});
      }).fadeIn("slow");
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

not forgetting of course that if you want this to loop as indicated you'd have to use .removeClass in the bit within the if statement and add an else for the remaining code, otherwise it's just a one way trip.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.