Skip to content

Instantly share code, notes, and snippets.

@dcatkins40
Last active December 11, 2015 10:29
Show Gist options
  • Save dcatkins40/4587553 to your computer and use it in GitHub Desktop.
Save dcatkins40/4587553 to your computer and use it in GitHub Desktop.
Javascript code to use Flexslider to change a background image after each slide change.
$(document).ready(function() {
var imgArr = new Array (
<?php
$total = count(get_field('field'));
$count = 1;
while(the_repeater_field('field', $pagenumber)): ?>
'<?php the_sub_field('sub_field'); ?>'<?php if($count < $total){echo ',';} $count++; ?>
<?php endwhile; ?>
);
var n = 0;
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
});
}
preload(imgArr);
$('.flexslider').flexslider({
start: function(slider) {
$('#container').attr('style', 'background-image: url(' + imgArr[n] + '); background-position: center; background-repeat: no repeat; background-size: cover;');
},
before: function(slider) {
},
after: function(slider) {
n = slider.currentSlide;
$('#container').attr('style', 'background-image: url(' + imgArr[n] + '); background-position: center; background-repeat: no repeat; background-size: cover;');
}
});
});
@KKAgrawal
Copy link

I have also tried to implement this, but I have not found it working. then I have replaced the img tag with the following

<div style="background-image: url('.$slide['url'].'); background-repeat: no repeat; background-size: cover;height:100%; width:100%;" ></div>

It worked very well without distorting the image in background. but for it, you have to set the height of

  • tag(Parent of div) and we don't need to implement flex slider "start, before, after" callback.

  • Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment