Search code examples
javascriptjqueryhtmlsupersized

Add atrributes from image to javascript array and display


I need to add the attributes from the images inside this div to an JS array and run Supersized, with these images:

       <div id="dgaslides">
            <img src="img/temp/topimg01.jpg" title="Image 1">
            <img src="img/temp/topimg02.jpg" title="Image 2">
            <img src="img/temp/topimg03.jpg" title="Image 3">
        </div>

My JS:

jQuery(function($){

var img_length = $('#dgaslides img').length-1;

var dgaslides = [];

$('#dgaslides img').each( function(i){

    var src     = $(this).attr('src');
    var title   = $(this).attr('title');

    dgaslides.push("{image : '" + src + "', title : '" + title + "'}");

    if(img_length == i){

        $.supersized({

            // Functionality
            slide_interval          :   3000,       // Length between transitions
            transition              :   1,          // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
            transition_speed        :   700,        // Speed of transition
            horizontal_center       :   1,          // Centers image horizontally. When turned off, the images resize/display from the left of the page.


            // Components                           
            slide_links             :   'blank',    // Individual links for each slide (Options: false, 'num', 'name', 'blank')
            slides                  :   dgaslides

        });

    }
}); });

It does work, as im getting 3 images in my output, but the link (src) is "Undefined", and the title isn't there either?

The right way to hardcode it is:

var dgaslides = [           // Slideshow Images
                {image : 'img/temp/topimg01.jpg', title : 'Reception'},
                {image : 'img/temp/topimg02.jpg', title : 'Reception 2 og noget mere tekst her'},  
                {image : 'img/temp/topimg03.jpg', title : 'Reception 3'}
            ];

Can anyone help me figuring out what i'm doing wrong?


Solution

  • You could use jQuery's map method to simplify the task. Following is the code.

    jQuery(function ($) {
        var dgaslides = $('#dgaslides img').map(function () {
          return {
            image: $(this).attr('src'),
            title: $(this).attr('title')
          };
        });
        $.supersized({
          slide_interval: 3000,
          transition: 1,
          transition_speed: 700,
          horizontal_center: 1,                   
          slide_links: 'blank',
          slides: dgaslides
        });
    });
    

    Hope this helps.