Subscribe

Monday 22 March 2010

YouTube Video Feed Slide-Show Gadget With JQuery Part 2

This is the second part in my ongoing series of posts which will show you how to get You-Tube video feed and build a simple carousel or slide-show for yourself. If you have not read the first part, please make sure you do so here Part1.
Target For The Post
A Javascript class which uses jquery and the youtube class designed earlier to create a slide show or carousel in any document or website.

Class To Design

  1. tubeslider
  2. SlideTimer
tubeslider methods
  1. initex(tube_data)
  2. start()
  3. stop()
tubeslider class variables

   1. this.timer_obj -----> stores the object of SlideTimer class
   2. this.timer_interval -> stores the user-defined speed in milliseconds
   3. this.divid ----------> stores the original div given by the user where this slider will be created
   4.  this.slider ---------> stores the new div created by the program used to slide the images or videos
   5.  this.master --------> stores the string to identify the main div given by the user, for jQuery it has a #                    infront of it

global variables

  1. var thumb_width -----> stores the thumb width
  2. var master_width -----> stores the mast_div width
  3. var thumb_height------> stores the thumb height

tubeslider constructor

   function(doc, divid, timer_interval) 
parameter doc is for future use and is not used anywhere at present
divid is the id of the div where you want your slider or gadget to reside
timer_interval is the speed in which you want the slider to move

remove any previous instance of the SlideTimer class and attach the CSS stylesheet to the document.

 if (this.timer_obj != null && this.timer_obj != undefined) {
        this.timer_obj.stop();
        delete this.timer_obj;
    }

    this.timer_obj = null;
    var slider_css = document.createElement('link');
    slider_css.rel = 'stylesheet'
    slider_css.type = 'text/css';
    slider_css.href = 'youtubeslider.css';
    document.getElementsByTagName('head')[0].appendChild(slider_css);
This function is the main function for this class, it receives the data in double dimension array called tube_data, then it initializes the thumb_width and height based on the data which is available and not the any random value, by default all the thumb size should be the same yet we search for the first legitimate thumb size and use it in our program.
var j = 0;
        while (j < tube_data.length && tube_data[j]["thumb_url"] == '#') {
            j++;
        }
        if (j >= tube_data.length)
            return -1;
        var k = 0;
        for (var i_loop = 0; i_loop < tube_data.length; i_loop++) {
            if (tube_data[i_loop]['thumb_url'] != '#')
                k++;
        }
        master_width = (parseInt(tube_data[j]["thumb_width"]) + 10) * (k);
        thumb_width = parseInt(tube_data[j]["thumb_width"]);
        thumb_height = parseInt(tube_data[j]["thumb_height"]);
Next we remove any previous divs inside the main div and create two divs one as the container for the slider and one for the player or the window where the video will be played when it is clicked. The div is also inside the main div thus it cannot be created outside the main div body. Inside the player div there are two divs first one has a link when clicked it will close the window and the other one will house the player. Then we create the slider div to house all the clickable thumbnails
var temp2 = temp + ' > div';
        $(temp2).remove();
        $(temp).css('position', 'absolute');
        $(temp).append("
"); $(temp).append("
" + "
"); var close_win = '#' + this.divid + '_close'; var temp_id2 = this.divid; $(close_win).click(function(event) { event.preventDefault(); if (temp_id2.charAt(0) != '#') temp_id2 = '#' + temp_id2 + '_player'; $(temp_id2).hide(); }); var master_id1 = '#' + this.divid + '_player'; var player_width1 = parseInt($(master_id1).css('width')); var player_height1 = parseInt($(master_id1).css('height')) - 17; //div to show the text temp2 += ":first"; this.master = temp + "master"; this.slider = this.divid + '_slider'; $(this.master).addClass('master'); $(this.master).append("
");
Next step is to create a image as link for the the videos which has been sent through tube_data, when we draw these images we must make sure that the url property has a valid url and not a # symbol, which signifies that the video has been blocked by the content provider.
 this.slider = '#' + this.slider;
        for (var i = 0; i < tube_data.length; i++) {
            if (tube_data[i]["thumb_url"] != '#') {
                var div_tag = "
"; var a_tag = ""; var img_tag = ""; var ending_tags = "" + tube_data[i]['thumb_title'] + "(vid " + tube_data[i]['vid'] + ")" + "
"; $(this.slider).append(div_tag + a_tag + img_tag + ending_tags); } }
After we have the slider ready to rumble the next thing is to create a timer object so that at a predefined interval the slider div is moved by a certain amount. If mouse is hovered over the images it must stop the slide or the timer until the mouse moves out of the div. In this we use jquery $.hover() function which gives us the opportunity to declare two functions one is fired when mouse is moved over and the second is fired when the mouse is moved out. For ease of programming we have used anonymous functions.
        var local_slider = this.slider;
        var local_master = this.master;
        var temp_del = this.slider + " > div"
        this.timer_obj = new SlideTimer(this.slider, this.master, this.timer_interval, this);
        var timer_obj_ref = this.timer_obj;

$(temp_del).hover(function() {
            timer_obj_ref.stop();
            var id_text = $(this).attr('id');
            if (id_text != undefined || id_text == '') {
                var i = id_text.length - 1;

                var chr_txt = id_text.charAt(i);
                while (!isNaN(parseInt(chr_txt))) {
                    i--;
                    var chr_txt = id_text.charAt(i);
                }
                id_text = id_text.substr(0, (i + 1));
                var txt_div = '#' + id_text + '_text';

                $(txt_div).css('display', 'block');
                $(txt_div).html("" + $(this).text() + "");



            }

        },
        function() {
            timer_obj_ref.start();
            var id_text = $(this).attr('id');
            if (id_text != undefined || id_text == '') {
                var i = id_text.length - 1;

                var chr_txt = id_text.charAt(i);
                while (!isNaN(parseInt(chr_txt))) {
                    i--;
                    var chr_txt = id_text.charAt(i);
                }
                id_text = id_text.substr(0, (i + 1));
                var txt_div = '#' + id_text + '_text';
                $(txt_div).css('display', 'none');
            }

        });

Lets say you want to watch some particular video, the logical thing will be to click on the image and it should play. To do so we must trap the click event and show the player div which we created earlier with the embedded player and the correct url.
var master_id = this.divid;
        $(temp_del).click(function(event) {
            timer_obj_ref.stop();
            event.preventDefault();
            var vid_text = $(this).text();

            if (vid_text != undefined || vid_text == '') {
                var i = vid_text.length - 1;
                var vid_mark1 = vid_text.indexOf('(vid');
                var vid_mark2 = -1;
                if (vid_mark1 != -1) {
                    vid_mark1 += 4;
                    vid_text = vid_text.substr(vid_mark1, ((vid_text.length - 1) - vid_mark1));
                }

                var playerid = '#' + master_id + '_player';
                vid_text = vid_text.replace(/^\s+|\s+$/g, "");

                var player_width = parseInt($(playerid).css('width'));
                var player_height = parseInt($(playerid).css('height'));

                var str_player = '<object style="position:relative;display:block;top:15px;left:1px;height' +
                (player_height - 17).toString() + 'px; width:' + (player_width - 2).toString() + 'px">' +
                '<param name="movie" value="http://www.youtube.com/v/' + vid_text +
                '?version=3&iv_load_police=3&autoplay=1&color1=0xb1b1b1&color2=0xcfcfcf&feature=player_embedded">' +
                '<param name="allowFullScreen" value="true">' +
                '<param name="allowScriptAccess" value="always">' +
                '<embed src="http://www.youtube.com/v/' + vid_text +
                '?version=3&iv_load_police=3&autoplay=1&color1=0xb1b1b1&color2=0xcfcfcf&feature=player_embedded" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="' +
                 (player_width - 2).toString() + '" height="' + (player_height - 17).toString() + '"></object>'

                $(playerid).css('display', 'block');

                var player_div = '#' + master_id + '_ytapiplayer';
                $(player_div).html(str_player);

            }
        });

The next two functions are trivial, they just start or stops the slide action for the user, actually it starts or stops the timer through the timer object declared earlier.
this.start = function() {
        if (this.timer_obj != null && this.timer_obj != undefined)
            this.timer_obj.start();
    }
    this.stop = function() {
        if (this.timer_obj != null && this.timer_obj != undefined)
            this.timer_obj.stop();
        delete (this.timer_obj);
        this.timer_obj = null;
    }
This is the complete code for our tubeslider class now comes the timer class which controls the timer object.

  SlideTimer Variables


 1. this.slider = slider; 
 2. this.master = master; 
 3. this.obj = slide_obj;
 4. this.timer_interval = timer_interval; 5. this.timerid = null;

SlideTimer Methods


1. start()
2. stop()
3. slideImages()

The first two methods are trivial they just initiate a setInterval function in the start method and clearInterval in the stop method. The only point to be noted is that setInterval creates an anonymous function which in turn calls the slideImages method.This is done in this way because a normal setInterval takes the function name only and does not allow you to prefix it with this to show a class method.
slideImages function uses the jQuery animate function to move the slider on the left by a fixed amount, if the whole slider has moved out of the screen i.e. it is no longer visible the start position is reintialized to the extreme left of the master div which we created in the earlier class as wrapper for the slider and player div.




SlideTimer = function(slider, master, timer_interval, slide_obj) {

    this.slider = slider;

    this.master = master;

    this.obj = slide_obj;

    this.timer_interval = timer_interval;

    this.timerid = null;

    this.start = function() {

       

        thisobject = this;

        this.timerid = setInterval(function() { thisobject.slideImages(); }, this.timer_interval); //"' + slider + '","' + master + '","' + obj + '")', 6000);



    }

    this.stop = function() {

        clearInterval(this.timerid);

    }





    this.slideImages = function() {

       

        var left_attr = parseInt($(this.slider).css('left'));

        var width_attr = parseInt($(this.master).css('width'));

        var slider_width = parseInt($(this.slider).css('width'));

        var animate_str = '-=' + thumb_width.toString();

        if (left_attr > (1 - (slider_width - Math.ceil((thumb_width ))))) {

            left_attr -= thumb_width;



        }

        else {

            left_attr = width_attr - (thumb_width * 2);

           

            $(this.slider).css('left', left_attr.toString() + 'px');

          

        }

     

        $(this.slider).animate({ left: animate_str }, 'slow');

       



    }

}





If you want to download the whole code please go to http://coolnerdblogger.com/mydownloads/YoutubeSlide/YouTubeSlide.php
If you want to test it out first then visit
http://coolnerdblogger.com/mydownloads/YoutubeSlide/jQueryAndYouTube.html
For more updates subscribe to my feed and checkout the videos of these posts, the video for the first part is already online check it out.

1 comment:

  1. Hi

    Congrats for your great blog about the amazing world of widgets.
    I'm searching a very easy (online?) widget creator tool to make a headline widget from a rss news feed. Do you know a free/cheap online programm to make this?

    ReplyDelete

 
EatonWeb Blog Directory