27

i have a list of images which i am getting through ajax and then using jquery $.each() i loop through the images and display a image one after the other after an interval of one second. I want the user to be able click on a stop button and so that the user can stop at a particular image if he wants to. So i need to dynamically exit $.each() when the user clicks on the stop button. Is it possible to do it?

peter
  • 3,411
  • 5
  • 24
  • 27

5 Answers5

59

You can use return false to break out of each() loops early.

Example:

<script>
    $("button").click(function () {
      $("div").each(function (index, domEle) {
        // domEle == this
        $(domEle).css("backgroundColor", "yellow"); 
        if ($(this).is("#stop")) {
          $("span").text("Stopped at div index #" + index);
          return false;
        }
      });
    });

</script>

Source: http://api.jquery.com/each/

Brad
  • 159,648
  • 54
  • 349
  • 530
Adeel
  • 19,075
  • 4
  • 46
  • 60
  • once a get the data through a ajax call i pass the data to a function show_images(data){ if($('#stop').is(':visible')){ return false; }else{ //diplay next image } } $(".stop").click(function(){ $("#stop").hide(); }); this does not work – peter Jun 04 '10 at 11:47
  • 2
    But you must return `false`. You cannot early return with `true`. – Jess Jun 02 '14 at 20:14
13

To break out of an each() loop you would:

return false;

So your button could set a variable when clicked that the each loop checks each pass, then returns false when the variable is set.

http://api.jquery.com/each/

user113716
  • 318,772
  • 63
  • 451
  • 440
4

http://api.jquery.com/each/

We can stop the loop from within the callback function by returning false.

Anpher
  • 4,567
  • 24
  • 24
3
return(false);

should do it.

jAndy
  • 231,737
  • 57
  • 305
  • 359
-1

Use return false; between each loop.

Andrew
  • 13,757
  • 13
  • 66
  • 84
Rifky
  • 1,444
  • 11
  • 26