skip to Main Content

i have a javascript object that contains video information(title and src url). In my HTML i have image placeholders and what i’m trying to do is when someone clicks on an image, a modal pops up (twitter bootstrap modal) of that specific video. i’m thinking of using HTML5’s data-attribute to link the title of the element to the title of the javascript object as a reference so that i can then insert the proper src url in the modal popup, but when i click on an image, i’m not getting the right url. I’m having trouble reference the data-attribute to the proper src url in the JavaScript object. I’m trying to learn and would appreciate some insight to a viable solution. Any help is greatly appreciated!

fiddle

EDIT
i realized that the for loop is ending on the last object, so when i reference the srcMp4 property, i’m ending up with the last one. so when i click on any of the posters, its referencing that value…i’ll continue investigating…

JavaScript

var dataCollection = {
    'videoData': [
      {
        'id'      : 0,
        'title'   : 'Badminton',
        'company' : 'Pepto Bismol',
        'gifLink' : 'http://reneinla.com/kris/gifs/BadmintonPeptoBismolCommercial.gif',
        'srcMp4'  : 'http://reneinla.com/kris/videos/BadmintonPeptoBismolCommercial.m4v',
        'srcWebm' : 'http://reneinla.com/kris/videos/BadmintonPeptoBismolCommercial.webm',
        'srcOgv'  : 'http://reneinla.com/kris/videos/BadmintonPeptoBismolCommercial.ogv',
        'poster'  : 'http://reneinla.com/kris/videos/BadmintonPeptoBismolCommercial.jpg'
      },
      {
        'id'      : 1,
        'title'   : 'Home Brewer',
        'company' : 'Buffalo Wild Wings',
        'gifLink' : 'http://reneinla.com/kris/gifs/BuffaloWildWingsHomeBrewer.gif',
        'srcMp4'  : 'http://reneinla.com/kris/videos/BuffaloWildWingsHomeBrewer.m4v',
        'srcWebm' : 'http://reneinla.com/kris/videos/BuffaloWildWingsHomeBrewer.webm',
        'srcOgv'  : 'http://reneinla.com/kris/videos/BuffaloWildWingsHomeBrewer.ogv',
        'poster'  : 'http://reneinla.com/kris/videos/BuffaloWildWingsHomeBrewer.jpg'
      },
      {
        'id'      : 2,
        'title'   : 'Directly to Fabulous',
        'company' : 'California Lottery',
        'gifLink' : 'http://reneinla.com/kris/gifs/CaliforniaLottoMonopolyGoDirectlytoFabulous.gif',
        'srcMp4'  : 'http://reneinla.com/kris/videos/CaliforniaLottoMonopolyGoDirectlytoFabulous.m4v',
        'srcWebm' : 'http://reneinla.com/kris/videos/CaliforniaLottoMonopolyGoDirectlytoFabulous.webm',
        'srcOgv'  : 'http://reneinla.com/kris/videos/CaliforniaLottoMonopolyGoDirectlytoFabulous.ogv',
        'poster'  : 'http://reneinla.com/kris/videos/CaliforniaLottoMonopolyGoDirectlytoFabulous.jpg'
      }
    ]
};

$(function() {
   var videos = $('#videos');
   var modalContent = $('#insert-here');

   for (var i = 0; i < dataCollection.videoData.length; i++) {
     var obj = dataCollection.videoData[i];
     // variable for poster image
     var video = obj.poster; 

     videos.append('<div class="video"><img src="' + obj.poster + '" data-title="' + obj.title + '"/></div>');
     $('.video img').click(function(){
     //modalContent.append('<video src="' + obj.srcMp4 + '"></video>');

       // debug
       alert(obj.srcMp4);
       console.log(obj.srcMp4);
     });
 }

});

HTML

<div class="container row">
   <div id="videos"></div>
</div>

// this is going to be bootstrap modal, but just as an example...
<div class="modal container">
   <div id="insert-here"></div>
</div>

6

Answers


  1. Remove click event from for loop I had changed code check on below Fiddle:

    https://jsfiddle.net/tc6advL3/

    for (var i = 0; i < dataCollection.videoData.length; i++) {
    var obj = dataCollection.videoData[i];
    // variable for poster image
    var video = obj.poster; 
    videos.append('<div class="video"><img src="' + obj.poster + '" data-title="' + obj.title + '" data-srcMp4="'+obj.srcMp4+'"/>
    </div>');
    
    }
    
    $('.video img').click(function(){
        //modalContent.append('<video src="' + obj.srcMp4 + '"></video>');
        alert($(this).attr("data-srcMp4"));
        console.log(obj.srcMp4);
    });
    
    Login or Signup to reply.
  2. The problem is in your loop. Your click event is triggered inside the loop. So it is overridden every time when the loop reaches the next image. I’ve updated your fiddle. By adding extra changes to your code. See below,

    for (var i = 0; i < dataCollection.videoData.length; i++) {
      var obj = dataCollection.videoData[i];
        // variable for poster image
        var video = obj.poster; 
        videos.append('<div class="video"><img src="' + obj.poster + '" data-title="' + obj.title + '" data-srcmp="'+obj.srcMp4+'"/></div>');
    
    }
    
     $('.video img').click(function(){
            //modalContent.append('<video src="' + obj.srcMp4 + '"></video>');
            alert($(this).data("srcmp"));
            console.log($(this).data("srcmp"));
        });
    

    fiddle

    Login or Signup to reply.
    1. You’re listening to click on .video img each time in the loop, it means the earlier the video is attached, the more times it’ll trigger the function.

    2. When the loop is end, the obj is point to the last element in the array, so all of the click will just alert the last video Object, you have to create a function and pass the object so the function can keep the obj for you.

    By this way, you can bind the obj to the created element, and you don’t have to set all the format on div one by one.

    var videos = $('#videos');
    var modalContent = $('#insert-here');
    
    var appendVideo = function(videoObj) {
        var poster = videoObj.poster;
        // Create the video element first, as we're going to listen to its img's click event.
        var video = $('<div class="video"><img src="' + poster + '" data-title="' + videoObj.title + '"/></div>');
        videos.append(video);
        video.find('img').click(function(e) {
            // Now you can access any of the type
            // like videoObj.srcWebm ... etc
            alert(videoObj.srcMp4);
            console(videoObj.srcMp4);
        });
    };
    
    for (var i = 0; i < dataCollection.videoData.length; i++) {
      var obj = dataCollection.videoData[i];
        appendVideo(obj);
    }
    

    See jsfiddle

    Login or Signup to reply.
    1. Move your event assignment outside of the loop – you’re assigning the event multiple times to all elements matching your selector.

    2. Inside your event handler, you can use the clicked item’s data to display the correct video.

    Updated code:

    var dataCollection = {
        'videoData': [...]
    };
    
    $(function() {
      var videos = $('#videos');
      var modalContent = $('#insert-here');
    
      for (var i = 0; i < dataCollection.videoData.length; i++) {
        var obj = dataCollection.videoData[i];
        // variable for poster image
        var video = obj.poster;
        videos.append('<div class="video"><img src="' + obj.poster + '" data-title="' + obj.title + '" data-srcMp4="' + obj.srcMp4 + '" /></div>');
    
      }
    
      $('.video img').click(function(){
        modalContent.empty().append('<video src="' + $(this).data().srcmp4 + '"></video>');
      });
    
    });
    

    JSFiddle: https://jsfiddle.net/mc939cqt/

    Login or Signup to reply.
  3. Seems like you would need to create a function that iterates through that object given a title.

    function getVideoByTitle(dataCollection, title) {
        for (var i = 0; i < dataCollection.videoData.length; i++) {
            var obj = dataCollection.videoData[i];
            if (obj.title == title) {
                //Do whatever you need to do with the data
            }
        }
        //here you should make sure that you handle for a case where there was something wong
    }
    

    And you would also need to create the on click event to send the information to that function.

    $('.video img').each(function () {
        var $this = $(this);
        $this.on("click", function () {
           getVideoByTitle(dataCollection, $(this).data('title'));
        });
    });
    

    I haven’t plugged this into your fiddle to test it but I think this idea might get you on the right path.

    Login or Signup to reply.
  4. I think obj variable is not accessible in event body. following code bind object to one element:

    $('.video img').data('video', obj);
    

    and access that object by following code:

    $('.video img').click(function(){
        //modalContent.append('<video src="' + obj.srcMp4 + '"></video>');
        alert($(this).data('video').srcMp4);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search