When the page is loading for the first time, I need to check if there is an image in image_array
and load the last image.
Otherwise, I disable the preview buttons, alert the user to push new image button and create an empty array to put the images;
The problem is that image_array
in the else
fires all time. If an array exists - it just overrides it, but alert doesn't work.
if(image_array.length > 0) $('#images').append('<img src="'+image_array[image_array.length-1]+'" class="images" id="1" />'); else{ $('#prev_image').attr('disabled', 'true'); $('#next_image').attr('disabled', 'true'); alert('Please get new image'); var image_array = []; }
UPDATE Before loading html, I have something like this:
<?php if(count($images) != 0): ?> <script type="text/javascript"> <?php echo "image_array = ".json_encode($images);?> </script> <?php endif; ?>
The array can be checked if it is empty by using the array. length property. This property returns the number of elements in the array. If the number is greater than 0, it evaluates to true.
length) // array null or empty check; if(array && ! array. length) // array exists, but empty check; if(str) // string not null and not empty.
Use the Object. entries() function. It returns an array containing the object's enumerable properties. If it returns an empty array, it means the object does not have any enumerable property, which in turn means it is empty.
if (typeof image_array !== 'undefined' && image_array.length > 0) { // the array is defined and has at least one element }
Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var
whenever declaring a variable:
<?php echo "var image_array = ".json_encode($images);?> // add var ^^^ here
And then make sure you never accidently redeclare that variable later:
else { ... image_array = []; // no var here }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With