Looping through an array to populate the variables for nivoSlider with each slide having its own settings -- [Question Asked]

Issue

This is my third attempt at asking this question differently regarding the population of nivoSlider setting with data returned by a query. Here I have tried to provide a better explanation of what I am trying to do.

This is what I am trying to do. I have two records in the table which contain the image name, effect, slices, boxCols, boxRows, animSpeed and pauseTime.

Run the script which returns the data and displays the images for each record using nivoSlider. Each slide has different display requirement, example:

Slide No1:
effect – sliceUp
slices – 30
boxCols – 16
boxRows – 8
animSpeed – 8000
pauseTime – 12000

Slide No2:

effect – boxRain
slices – 10
boxCols – 12
boxRows – 8
animSpeed – 8000
pauseTime – 6000

The nivoSlider script looks like:

$(window).load(function() {
  $('#slider').nivoSlider({
    effect: '<?php echo $row['Effect'];?>',
    slices:  '<?php echo $rowe['Slices'];?>',
    boxCols:'<?php echo $row['Cols'];?>',
    boxRows:  '<?php echo $row['Rows'];?>',
    animSpeed:'<?php echo $row['AnimSpeed'];?>',
    pauseTime: '<?php echo $row['TimeLapse'];?>',
    startSlide: 0,
    directionNav: false,
    controlNav: false,
    controlNavThumbs: false,
    pauseOnHover: false,
    manualAdvance: false,
    randomStart: false,
    beforeChange: function(){},
    afterChange: function(){},
    slideshowEnd: function(){},
    lastSlide: function(){},
    afterLoad: function(){}
  });
});

I then have a PHP loop to display each image one after the other:

<div class="slider-wrapper theme-default">
  <div id="slider" class="nivoSlider">
   <?php while($row_Signage = mysqli_fetch_assoc($result)) {?>
    <script type="text/javascript">
    $(window).load(function() {
      $('#slider').nivoSlider({
        effect: '<?php echo $row['Effect'];?>',
        slices:  '<?php echo $row['Slices'];?>',
        boxCols:'<?php echo $row['Cols'];?>',
        boxRows:  '<?php echo $row['Rows'];?>',
        animSpeed:'<?php echo $row['AnimSpeed'];?>',
        pauseTime: '<?php echo $row['TimeLapse'];?>',
        startSlide: 0,
        directionNav: false,
        controlNav: false,
        controlNavThumbs: false,
        pauseOnHover: false,
        manualAdvance: false,
        randomStart: false,
        beforeChange: function(){},
        afterChange: function(){},
        slideshowEnd: function(){},
        lastSlide: function(){},
        afterLoad: function(){}
      });
    });
    </script>
    <?php
      echo '<img src="/'.$ImagePath .''.$row['PromotionImage'].'"/> ';
    ?>
    <?php } ?>
  </div>
</div>

With the nivoSlider script inside of the while loop I expected the code to get the first record and display it using the variable in the nivoSlider script. It does display the images but it also displays a blank page with the error:

example.com/apps/signage/EXBHX/DS2/undefined.

It has been suggested that I need to move a part of the code outside of the while loop, so I tried this:

<?php while($row = mysqli_fetch_assoc($result)) {
  $effect = $row['Effect'];
  $slices = $row['Slices'];
  $boxCols = $row['Cols'];
  $boxRows = $row['Rows'];
  $animSpeed = $row['AnimSpeed'];
  $pauseTime = $row['TimeLapse'];
?>

<script type="text/javascript">
$(window).load(function() {
  $('#slider').nivoSlider({
    effect: '<?php echo $effect;?>',
    slices:  '<?php echo $slices;?>',
    boxCols:'<?php echo $boxCols;?>',
    boxRows:  '<?php echo $boxRows;?>',
    animSpeed:'<?php echo $animSpeed ;?>',
    pauseTime: '<?php echo $pauseTime;?>',
    startSlide: 0,
    directionNav: false,
    controlNav: false,
    controlNavThumbs: false,
    pauseOnHover: false,
    manualAdvance: false,
    randomStart: false,
    beforeChange: function(){},
    afterChange: function(){},
    slideshowEnd: function(){},
    lastSlide: function(){},
    afterLoad: function(){}
  });
});
</script>
<?php
  echo '<img src="/'.$ImagePath .''.$row['PromotionImage'].'"/> ';
?>
<?php } ?>

The above produces the following:

<script type="text/javascript">
$(window).load(function() {
$('#slider').nivoSlider({
effect: 'sliceUp',
slices:  '30',
boxCols:'16',
boxRows:  '8',
animSpeed:'8000',
pauseTime: '12000',
startSlide: 0,
directionNav: false,
controlNav: false,
controlNavThumbs: false,
pauseOnHover: false,
manualAdvance: false,
randomStart: false,
beforeChange: function(){},
afterChange: function(){},
slideshowEnd: function(){},
lastSlide: function(){},
afterLoad: function(){}
});
});
</script>
<img src="/apps/signage/promotion_images/EXBHX/boards/DS2/monday_portrait.png"/>
<script type="text/javascript">
$(window).load(function() {
$('#slider').nivoSlider({
effect: 'boxRain',
slices:  '10',
boxCols:'12',
boxRows:  '8',
animSpeed:'8000',
pauseTime: '6000',
startSlide: 0,
directionNav: false,
controlNav: false,
controlNavThumbs: false,
pauseOnHover: false,
manualAdvance: false,
randomStart: false,
beforeChange: function(){},
afterChange: function(){},
slideshowEnd: function(){},
lastSlide: function(){},
afterLoad: function(){}
});
});
</script>
<img src="/apps/signage/promotion_images/EXBHX/boards/DS2/tuesday_portrait.png"/>

This does not work, it displays the same:

error: example.com/apps/signage/EXBHX/DS2/undefined

This does not stop the script from running but it does display a blank page at the start of the display loop.

I could write more on the different ways I have ordered the code but nothing works.

Code from the library:

Line 90 to line 111

    //Create caption
    slider.append($('<div class="nivo-caption"></div>'));
    
    // Process caption function
    var processCaption = function(settings){
        var nivoCaption = $('.nivo-caption', slider);
        if(vars.currentImage.attr('title') != '' && vars.currentImage.attr('title') != undefined){
            var title = vars.currentImage.attr('title');
            if(title.substr(0,1) == '#') title = $(title).html();   

            if(nivoCaption.css('display') == 'block'){
                setTimeout(function(){
                    nivoCaption.html(title);
                }, settings.animSpeed);
            } else {
                nivoCaption.html(title);
                nivoCaption.stop().fadeIn(settings.animSpeed);
            }
        } else {
            nivoCaption.stop().fadeOut(settings.animSpeed);
        }
    }
    

Line 210 to line 240

    // Add slices for slice animations
    var createSlices = function(slider, settings, vars) {
        if($(vars.currentImage).parent().is('a')) $(vars.currentImage).parent().css('display','block');
        $('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').width(slider.width()).css('visibility', 'hidden').show();
        var sliceHeight = ($('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').parent().is('a')) ? $('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').parent().height() : $('img[src="'+ vars.currentImage.attr('src') +'"]', slider).not('.nivo-main-image,.nivo-control img').height();

        for(var i = 0; i < settings.slices; i++){
            var sliceWidth = Math.round(slider.width()/settings.slices);
            
            if(i === settings.slices-1){
                slider.append(
                    $('<div class="nivo-slice" name="'+i+'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block !important; top:0; left:-'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px;" /></div>').css({ 
                        left:(sliceWidth*i)+'px', 
                        width:(slider.width()-(sliceWidth*i))+'px',
                        height:sliceHeight+'px', 
                        opacity:'0',
                        overflow:'hidden'
                    })
                );
            } else {
                slider.append(
                    $('<div class="nivo-slice" name="'+i+'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block !important; top:0; left:-'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px;" /></div>').css({ 
                        left:(sliceWidth*i)+'px', 
                        width:sliceWidth+'px',
                        height:sliceHeight+'px',
                        opacity:'0',
                        overflow:'hidden'
                    })
                );
            }
        }

Line 256 to line 286

        for(var rows = 0; rows < settings.boxRows; rows++){
            for(var cols = 0; cols < settings.boxCols; cols++){
                if(cols === settings.boxCols-1){
                    slider.append(
                        $('<div class="nivo-box" name="'+ cols +'" rel="'+ rows +'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block; top:-'+ (boxHeight*rows) +'px; left:-'+ (boxWidth*cols) +'px;" /></div>').css({ 
                            opacity:0,
                            left:(boxWidth*cols)+'px', 
                            top:(boxHeight*rows)+'px',
                            width:(slider.width()-(boxWidth*cols))+'px'
                            
                        })
                    );
                    $('.nivo-box[name="'+ cols +'"]', slider).height($('.nivo-box[name="'+ cols +'"] img', slider).height()+'px');
                } else {
                    slider.append(
                        $('<div class="nivo-box" name="'+ cols +'" rel="'+ rows +'"><img src="'+ vars.currentImage.attr('src') +'" style="position:absolute; width:'+ slider.width() +'px; height:auto; display:block; top:-'+ (boxHeight*rows) +'px; left:-'+ (boxWidth*cols) +'px;" /></div>').css({ 
                            opacity:0,
                            left:(boxWidth*cols)+'px', 
                            top:(boxHeight*rows)+'px',
                            width:boxWidth+'px'
                        })
                    );
                    $('.nivo-box[name="'+ cols +'"]', slider).height($('.nivo-box[name="'+ cols +'"] img', slider).height()+'px');
                }
            }
        }
        
        sliderImg.stop().animate({
            height: $(vars.currentImage).height()
        }, settings.animSpeed);
    };

Line 356 to line 364

        // Run random effect from specified set (eg: effect:'fold,fade')
        if(settings.effect.indexOf(',') !== -1){
            anims = settings.effect.split(',');
            currentEffect = anims[Math.floor(Math.random()*(anims.length))];
            if(currentEffect === undefined) { currentEffect = 'fade'; }
        }
    

Solution

I have not used nivoslider before. Also, I can’t find any detailed doc for this plugin. So, I have decided to take a look at its code.

As I understood this plugin used common config (option) object for all of the images inside the slider.

I can’t find a way to change the attributes for each image by default.

So, I have decided to edit the library code.

My goal is simple. Instead of taking the slider attributes from the option, I want to pass those attributes inside img tag like data-nseffect='boxRain'. then in the library, I want to access it like .data('nseffect').

Here the changes I have made in the library.

Line Number: 361

  var currentEffect = vars.currentImage.data('nseffect') || settings.effect;
  console.log('effect', currentEffect);

Line Number: 223

  settings.slices = vars.currentImage.data('nsslices') || settings.slices;
  console.log('slices', settings.slices);

Line Number: 263

  settings.boxCols = vars.currentImage.data('nsboxcols') || settings.boxCols;
  console.log('boxCols', settings.boxCols);

  settings.boxRows = vars.currentImage.data('nsboxrows') || settings.boxRows;
  console.log('boxRows', settings.boxRows);

Line Number: 99

  settings.animSpeed = vars.currentImage.data('nsanimspeed') || settings.animSpeed;
  console.log('animSpeed', settings.animSpeed);

Unfortunately, It takes pauseTime only from the 1st img attribute and creates a setInterval So, It should be common to all of the images inside the slider.

Here the HTML part.

    <div id="slider" class="nivoSlider">
        <img src="images/toystory.jpg"
        data-thumb="images/toystory.jpg"
        alt = ""
        data-nseffect = "boxRain"
        data-nsslices = "30"
        data-nsboxcols = "10"
        data-nsboxrows = "5"
        data-nsanimspeed = "5000"
        data-nspausetime = "3000"
        />

        <a href="http://dev7studios.com">
          <img src="images/up.jpg"
          title="This is an example of a caption"
          data-nseffect = "sliceUp"
          data-nsslices = "35"
          data-nsboxcols = "15"
          data-nsboxrows = "6"
          data-nsanimspeed = "3000"
          data-nspausetime = "3000"
           />
        </a>

      ...
      ...

    </div>

Finally in PHP

<div id="slider" class="nivoSlider">
 <?php while($row = mysqli_fetch_assoc($result)) {
 $effect = $row['Effect'];
 $slices = $row['Slices'];
 $boxCols = $row['Cols'];
 $boxRows = $row['Rows'];
 $animSpeed = $row['AnimSpeed'];
 $pauseTime = $row['TimeLapse'];
 echo '<img src="/'.$ImagePath .''.$row['PromotionImage'].'"
    data-nseffect = "'.$effect.'"
    data-nsslices = "'.$slices.'"
    data-nsboxcols = "'.$boxCols.'"
    data-nsboxrows = "'.$boxRows.'"
    data-nsanimspeed = "'.$animSpeed.'"
    data-nspausetime = "'.$pauseTime.'"
    />';
  }?>
</div>
...
<script type="text/javascript">
$(window).load(function() {
    $('#slider').nivoSlider();
});
</script>

Note: I took this library from their official GitHub here.

It works for me. Hope it will help you. üôÇ

Answered By – Prabu samvel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Posted in PHP

Who we are?

We are team of software engineers in multiple domains like Programming and coding, Fundamentals of computer science, Design and architecture, Algorithms and data structures, Information analysis, Debugging software and Testing software. We are working on Systems developer and application developer. We are curious, methodical, rational, analytical, and logical. Some of us are also conventional, meaning we're conscientious and conservative.

Answer collected from stackoverflow and other sources, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0