Script Re-sizing Webpage - javascript

I am currently using a Shooting Star script I found online to randomize shooting stars across the webpage. Whenever a shooting star goes out of the visible webpage, scroll bars appear and re-size the entire page for a moment. This happens quite frequently. Is there a way I can just have the shooting star delete itself once it hits the edge of the webpage, or maybe have it so that the webpage isn't affected by the shooting stars? Here's the website where I got the script from: http://codepen.io/manufosela/pen/Gymih
Here's the code:
<html>
<head>
<title>Shooting star Example</title>
<meta charset="utf-8">
<meta name="author" content="#manufosela">
</head>
<body class="stars">
<h1>SHOOTING STARS...</h1>
<div id="ShootingStarParams"></div>
<script type="text/javascript" src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="ShootingStarClass.js"></script>
<script type="text/javascript">
$( document ).ready( function(){
var shootingStarObj = new ShootingStar( "body" );
shootingStarObj.launch();
});
</script>
</body>
</html>
body { color:#FFF; height:600px; width:99%; height:95%; color:#FFF; }
.stars {
z-index: 0; position: absolute; /* width: 420em; height: 70em; */
background-image: url( http://www.14denoviembre.es/img/hori.png ), url( http://www.14denoviembre.es/img/stars_5.png ); background-repeat: repeat-x,repeat-x repeat-y;
transform:translate3D(0em, 0em, 0); animation: stars 21s ease; transform-style: preserve-3d;
}
(function(){
/**
author: #manufosela
2013/08/27 copyleft 2013
ShootingStar class Main Methods:
launch: launch shooting stars every N seconds received by param. 10 seconds by default.
launchStar: launch a shooting star. Received options object by param with:
- dir (direction between 0 and 1)
- life (between 100 and 400)
- beamSize (between 400 and 700)
- velocity (between 2 and 10)
**/
ShootingStar = function( id ) {
this.n = 0;
this.m = 0;
this.defaultOptions = { velocity:8, starSize:10, life:300, beamSize:400, dir:-1 };
this.options = {};
id = ( typeof id != "undefined" )?id:"";
this.capa = ( $( id ).lenght > 0 )?"body":id;
this.wW = $( this.capa ).innerWidth();
this.hW = $( this.capa ).innerHeight();
};
ShootingStar.prototype.addBeamPart = function( x, y ) {
this.n++;
var name = this.getRandom( 100, 1 );
$( "#star"+name ).remove();
$( this.capa ).append( "<div id='star"+name+"'></div>" );
$( "#star"+name ).append( "<div id='haz"+this.n+"' class='haz' style='position:absolute; color:#FF0; width:10px; height:10px; font-weight:bold; font-size:"+this.options.starSize+"px'>·</div>" );
if ( this.n > 1 ) $( "#haz" + ( this.n - 1 ) ).css( { color:"rgba(255,255,255,0.5)" } );
$( "#haz" + this.n ).css( { top: y + this.n, left: x + ( this.n * this.options.dir ) } );
}
ShootingStar.prototype.delTrozoHaz = function() {
this.m++;
$( "#haz" + this.m ).animate( {opacity:0}, 75 );
if ( this.m >= this.options.beamSize ) { $( "#ShootingStarParams" ).fadeOut( "slow" ); }
}
ShootingStar.prototype.getRandom = function( max, min ) {
return Math.floor( Math.random() * (max - min + 1)) + min;
}
ShootingStar.prototype.toType = function ( obj ) {
if ( typeof obj === "undefined" ) { return "undefined"; /* consider: typeof null === object */ }
if ( obj === null ) { return "null"; }
var type = Object.prototype.toString.call( obj ).match( /^\[object\s(.*)\]$/ )[1] || '';
switch ( type ) {
case 'Number': if ( isNaN( obj ) ) { return "nan"; } else { return "number"; }
case 'String': case 'Boolean': case 'Array': case 'Date': case 'RegExp': case 'Function': return type.toLowerCase();
}
if ( typeof obj === "object" ) { return "object"; }
return undefined;
}
ShootingStar.prototype.launchStar = function( options ) {
if ( this.toType( options ) != "object" ) { options = {}; }
this.options = $.extend( {}, this.defaultOptions, options );
this.n=0;
this.m=0;
var i=0, l=this.options.beamSize,
x=this.getRandom( this.wW - this.options.beamSize - 100, 100 ), y=this.getRandom( this.hW - this.options.beamSize - 100, 100 ),
self = this;
for( ; i<l; i++ ) { setTimeout( function(){ self.addBeamPart( x, y ); }, self.options.life + ( i * self.options.velocity ) ); }
for( i=0; i<l; i++ ) { setTimeout( function(){ self.delTrozoHaz() }, self.options.beamSize + ( i * self.options.velocity ) ); }
$( "#ShootingStarParams" ).html( "Launching shooting star. PARAMS: wW: " + this.wW + " - hW: " + this.hW + " - life: " + this.options.life + " - beamSize: " + this.options.beamSize + " - velocity: " + this.options.velocity );
$( "#ShootingStarParams" ).fadeIn( "slow" );
}
ShootingStar.prototype.launch = function( everyTime ) {
if ( this.toType( everyTime ) != "number" ) { everyTime = 10; }
everyTime = everyTime * 1000;
this.launchStar();
var self = this;
setInterval( function() {
var options = {
dir: ( self.getRandom( 1, 0 ))?1:-1,
life: self.getRandom( 400, 100 ),
beamSize: self.getRandom( 700, 400 ),
velocity: self.getRandom( 10, 4 )
}
self.launchStar( options );
}, everyTime );
}
})();

body {
overflow: hidden;
}
This prevents scrollbars from appearing when content of an element goes beyond its dimensions.

Related

curving text using button jquery

i would like to know how i can make more designs using http://circletype.labwire.ca/#fitText i was succesful on making one but that is about it it only makes a circle i cant make more designs something is wrong with my code can someone please help? also how can i make wedge text and "wiggle" text one last thing i would also like to know how to make spiral text if some one knows any of these it would be a great help
$("#fs").change(function() {
//alert($(this).val());
$('.changeMe').css("font-family", $(this).val());
});
$("#size").change(function() {
$('.changeMe').css("font-size", $(this).val() + "px");
});
$("#demo1").click(function(){
$('.changeMe').circleType("fitText:true", $(this).attr('radius: 180'));
});
/**
* Arctext.js
* A jQuery plugin for curved text
* http://www.codrops.com
*
* Copyright 2011, Pedro Botelho / Codrops
* Free to use under the MIT license.
*
* Date: Mon Jan 23 2012
*/
(function( $, undefined ) {
/*!
* FitText.js 1.0
*
* Copyright 2011, Dave Rupert http://daverupert.com
* Released under the WTFPL license
* http://sam.zoy.org/wtfpl/
*
* Date: Thu May 05 14:23:00 2011 -0600
*/
$.fn.fitText = function( kompressor, options ) {
var settings = {
'minFontSize' : Number.NEGATIVE_INFINITY,
'maxFontSize' : Number.POSITIVE_INFINITY
};
return this.each(function() {
var $this = $(this); // store the object
var compressor = kompressor || 1; // set the compressor
if ( options ) {
$.extend( settings, options );
}
// Resizer() resizes items based on the object width divided by the compressor * 10
var resizer = function () {
$this.css('font-size', Math.max(Math.min($this.width() / (compressor*10), parseFloat(settings.maxFontSize)), parseFloat(settings.minFontSize)));
};
// Call once to set.
resizer();
// Call on resize. Opera debounces their resize by default.
$(window).resize(resizer);
});
};
/*
* Lettering plugin
*
* changed injector function:
* add for empty chars.
*/
function injector(t, splitter, klass, after) {
var a = t.text().split(splitter), inject = '', emptyclass;
if (a.length) {
$(a).each(function(i, item) {
emptyclass = '';
if(item === ' ') {
emptyclass = ' empty';
item=' ';
}
inject += '<span class="'+klass+(i+1)+emptyclass+'">'+item+'</span>'+after;
});
t.empty().append(inject);
}
}
var methods = {
init : function() {
return this.each(function() {
injector($(this), '', 'char', '');
});
},
words : function() {
return this.each(function() {
injector($(this), ' ', 'word', ' ');
});
},
lines : function() {
return this.each(function() {
var r = "eefec303079ad17405c889e092e105b0";
// Because it's hard to split a <br/> tag consistently across browsers,
// (*ahem* IE *ahem*), we replaces all <br/> instances with an md5 hash
// (of the word "split"). If you're trying to use this plugin on that
// md5 hash string, it will fail because you're being ridiculous.
injector($(this).children("br").replaceWith(r).end(), r, 'line', '');
});
}
};
$.fn.lettering = function( method ) {
// Method calling logic
if ( method && methods[method] ) {
return methods[ method ].apply( this, [].slice.call( arguments, 1 ));
} else if ( method === 'letters' || ! method ) {
return methods.init.apply( this, [].slice.call( arguments, 0 ) ); // always pass an array
}
$.error( 'Method ' + method + ' does not exist on jQuery.lettering' );
return this;
};
/*
* Arctext object.
*/
$.Arctext = function( options, element ) {
this.$el = $( element );
this._init( options );
};
$.Arctext.defaults = {
radius : 0, // the minimum value allowed is half of the word length. if set to -1, the word will be straight.
dir : 1, // 1: curve is down, -1: curve is up.
rotate : true, // if true each letter will be rotated.
fitText : false // if you wanna try out the fitText plugin (http://fittextjs.com/) set this to true. Don't forget the wrapper should be fluid.
};
$.Arctext.prototype = {
_init : function( options ) {
this.options = $.extend( true, {}, $.Arctext.defaults, options );
// apply the lettering plugin.
this._applyLettering();
this.$el.data( 'arctext', true );
// calculate values
this._calc();
// apply transformation.
this._rotateWord();
// load the events
this._loadEvents();
},
_applyLettering : function() {
this.$el.lettering();
if( this.options.fitText )
this.$el.fitText();
this.$letters = this.$el.find('span').css('display', 'inline-block');
},
_calc : function() {
if( this.options.radius === -1 )
return false;
// calculate word / arc sizes & distances.
this._calcBase();
// get final values for each letter.
this._calcLetters();
},
_calcBase : function() {
// total word width (sum of letters widths)
this.dtWord = 0;
var _self = this;
this.$letters.each( function(i) {
var $letter = $(this),
letterWidth = $letter.outerWidth( true );
_self.dtWord += letterWidth;
// save the center point of each letter:
$letter.data( 'center', _self.dtWord - letterWidth / 2 );
});
// the middle point of the word.
var centerWord = this.dtWord / 2;
// check radius : the minimum value allowed is half of the word length.
if( this.options.radius < centerWord )
this.options.radius = centerWord;
// total arc segment length, where the letters will be placed.
this.dtArcBase = this.dtWord;
// calculate the arc (length) that goes from the beginning of the first letter (x=0) to the end of the last letter (x=this.dtWord).
// first lets calculate the angle for the triangle with base = this.dtArcBase and the other two sides = radius.
var angle = 2 * Math.asin( this.dtArcBase / ( 2 * this.options.radius ) );
// given the formula: L(ength) = R(adius) x A(ngle), we calculate our arc length.
this.dtArc = this.options.radius * angle;
},
_calcLetters : function() {
var _self = this,
iteratorX = 0;
this.$letters.each( function(i) {
var $letter = $(this),
// calculate each letter's semi arc given the percentage of each letter on the original word.
dtArcLetter = ( $letter.outerWidth( true ) / _self.dtWord ) * _self.dtArc,
// angle for the dtArcLetter given our radius.
beta = dtArcLetter / _self.options.radius,
// distance from the middle point of the semi arc's chord to the center of the circle.
// this is going to be the place where the letter will be positioned.
h = _self.options.radius * ( Math.cos( beta / 2 ) ),
// angle formed by the x-axis and the left most point of the chord.
alpha = Math.acos( ( _self.dtWord / 2 - iteratorX ) / _self.options.radius ),
// angle formed by the x-axis and the right most point of the chord.
theta = alpha + beta / 2,
// distances of the sides of the triangle formed by h and the orthogonal to the x-axis.
x = Math.cos( theta ) * h,
y = Math.sin( theta ) * h,
// the value for the coordinate x of the middle point of the chord.
xpos = iteratorX + Math.abs( _self.dtWord / 2 - x - iteratorX ),
// finally, calculate how much to translate each letter, given its center point.
// also calculate the angle to rotate the letter accordingly.
xval = 0| xpos - $letter.data( 'center' ),
yval = 0| _self.options.radius - y,
angle = ( _self.options.rotate ) ? 0| -Math.asin( x / _self.options.radius ) * ( 180 / Math.PI ) : 0;
// the iteratorX will be positioned on the second point of each semi arc
iteratorX = 2 * xpos - iteratorX;
// save these values
$letter.data({
x : xval,
y : ( _self.options.dir === 1 ) ? yval : -yval,
a : ( _self.options.dir === 1 ) ? angle : -angle
});
});
},
_rotateWord : function( animation ) {
if( !this.$el.data('arctext') ) return false;
var _self = this;
this.$letters.each( function(i) {
var $letter = $(this),
transformation = ( _self.options.radius === -1 ) ? 'none' : 'translateX(' + $letter.data('x') + 'px) translateY(' + $letter.data('y') + 'px) rotate(' + $letter.data('a') + 'deg)',
transition = ( animation ) ? 'all ' + ( animation.speed || 0 ) + 'ms ' + ( animation.easing || 'linear' ) : 'none';
$letter.css({
'-webkit-transition' : transition,
'-moz-transition' : transition,
'-o-transition' : transition,
'-ms-transition' : transition,
'transition' : transition
})
.css({
'-webkit-transform' : transformation,
'-moz-transform' : transformation,
'-o-transform' : transformation,
'-ms-transform' : transformation,
'transform' : transformation
});
});
},
_loadEvents : function() {
if( this.options.fitText ) {
var _self = this;
$(window).on( 'resize.arctext', function() {
_self._calc();
// apply transformation.
_self._rotateWord();
});
}
},
set : function( opts ) {
if( !opts.radius &&
!opts.dir &&
opts.rotate === 'undefined' ) {
return false;
}
this.options.radius = opts.radius || this.options.radius;
this.options.dir = opts.dir || this.options.dir;
if( opts.rotate !== undefined ) {
this.options.rotate = opts.rotate;
}
this._calc();
this._rotateWord( opts.animation );
},
destroy : function() {
this.options.radius = -1;
this._rotateWord();
this.$letters.removeData('x y a center');
this.$el.removeData('arctext');
$(window).off('.arctext');
}
};
var logError = function( message ) {
if ( this.console ) {
console.error( message );
}
};
$.fn.arctext = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'arctext' );
if ( !instance ) {
logError( "cannot call methods on arctext prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for arctext instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'arctext' );
if ( !instance ) {
$.data( this, 'arctext', new $.Arctext( options, this ) );
}
});
}
return this;
};
})( jQuery );
/*
* CircleType 0.36
* Peter Hrynkow
* Copyright 2014, Licensed GPL & MIT
*
*/
$.fn.circleType = function(options) {
var self = this,
settings = {
dir: 1,
position: 'relative',
};
if (typeof($.fn.lettering) !== 'function') {
console.log('Lettering.js is required');
return;
}
return this.each(function () {
if (options) {
$.extend(settings, options);
}
var elem = this,
delta = (180 / Math.PI),
fs = parseInt($(elem).css('font-size'), 10),
ch = parseInt($(elem).css('line-height'), 10) || fs,
txt = elem.innerHTML.replace(/^\s+|\s+$/g, '').replace(/\s/g, ' '),
letters,
center;
elem.innerHTML = txt
$(elem).lettering();
elem.style.position = settings.position;
letters = elem.getElementsByTagName('span');
center = Math.floor(letters.length / 2)
var layout = function () {
var tw = 0,
i,
offset = 0,
minRadius,
origin,
innerRadius,
l, style, r, transform;
for (i = 0; i < letters.length; i++) {
tw += letters[i].offsetWidth;
}
minRadius = (tw / Math.PI) / 2 + ch;
if (settings.fluid && !settings.fitText) {
settings.radius = Math.max(elem.offsetWidth / 2, minRadius);
}
else if (!settings.radius) {
settings.radius = minRadius;
}
if (settings.dir === -1) {
origin = 'center ' + (-settings.radius + ch) / fs + 'em';
} else {
origin = 'center ' + settings.radius / fs + 'em';
}
innerRadius = settings.radius - ch;
for (i = 0; i < letters.length; i++) {
l = letters[i];
offset += l.offsetWidth / 2 / innerRadius * delta;
l.rot = offset;
offset += l.offsetWidth / 2 / innerRadius * delta;
}
for (i = 0; i < letters.length; i++) {
l = letters[i]
style = l.style
r = (-offset * settings.dir / 2) + l.rot * settings.dir
transform = 'rotate(' + r + 'deg)';
style.position = 'absolute';
style.left = '50%';
style.marginLeft = -(l.offsetWidth / 2) / fs + 'em';
style.webkitTransform = transform;
style.MozTransform = transform;
style.OTransform = transform;
style.msTransform = transform;
style.transform = transform;
style.webkitTransformOrigin = origin;
style.MozTransformOrigin = origin;
style.OTransformOrigin = origin;
style.msTransformOrigin = origin;
style.transformOrigin = origin;
if(settings.dir === -1) {
style.bottom = 0;
}
}
if (settings.fitText) {
if (typeof($.fn.fitText) !== 'function') {
console.log('FitText.js is required when using the fitText option');
} else {
$(elem).fitText();
$(window).resize(function () {
updateHeight();
});
}
}
updateHeight();
if (typeof settings.callback === 'function') {
// Execute our callback with the element we transformed as `this`
settings.callback.apply(elem);
}
};
var getBounds = function (elem) {
var docElem = document.documentElement,
box = elem.getBoundingClientRect();
return {
top: box.top + window.pageYOffset - docElem.clientTop,
left: box.left + window.pageXOffset - docElem.clientLeft,
height: box.height
};
};
var updateHeight = function () {
var mid = getBounds(letters[center]),
first = getBounds(letters[0]),
h;
if (mid.top < first.top) {
h = first.top - mid.top + first.height;
} else {
h = mid.top - first.top + first.height;
}
elem.style.height = h + 'px';
}
if (settings.fluid && !settings.fitText) {
$(window).resize(function () {
layout();
});
}
if (document.readyState !== "complete") {
elem.style.visibility = 'hidden';
$(window).load(function () {
elem.style.visibility = 'visible';
layout();
});
} else {
layout();
}
});
};
<form id="myform">
<select id="fs">
<option value="Arial">Arial</option>
<option value="Verdana ">Verdana </option>
<option value="Impact ">Impact </option>
<option value="Comic Sans MS">Comic Sans MS</option>
</select>
<select id="size">
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="14">14</option>
<option value="16">16</option>
<option value="18">18</option>
<option value="20">20</option>
<option value="22">22</option>
<option value="24">24</option>
<option value="26">26</option>
<option value="28">28</option>
<option value="30">30</option>
<option value="32">32</option>
<option value="34">34</option>
<option value="36">36</option>
</select>
<div id="demo1">Here is some text I would like to see in a different shape.</div>
</form>
<br/>
<div id="container" class="changeMe">
Hello World 1234567890<div id="float">
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script><link rel="stylesheet"
href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://circletype.labwire.ca/js/circletype.js"></script>
<script src="https://tympanus.net/Development/Arctext/js/jquery.arctext.js"></script>
My guess is that your problem is with this code:
$("#demo1").click(function(){
$('.changeMe').circleType("fitText:true", $(this).attr('radius: 180'));
});
You do not have a proper div matching this code. I'll come back to this in a minute but first you should know that usually one does not go in and edit a library directly. My suggestion is that you play with your code inside of its own separate <script> tags.
So maybe after you finish loading your libraries:
<script>
$("#fs").change(function() {
//alert($(this).val());
$('.changeMe').css("font-family", $(this).val());
});
$("#size").change(function() {
$('.changeMe').css("font-size", $(this).val() + "px");
});
$("#demo1").click(function(){
$('.changeMe').circleType("fitText:true", $(this).attr('radius: 180'));
});
</script>
Then you just need to modify your HTML so that you have a demo1 div that is not a button:
<div id="demo1">Here is some text I would like to see in a different shape.</div>
This code probably likes to run against regular old HTML text and not a button.
Hope this helps!
UPDATE: I got rid of your redundant libraries and simplified your code. This example should work when placed between the <body> tags in an HTML document. Click each line to see it in action. I also moved your stylesheets into the document <head> tag where they belong.
<div id="demo1">Here is some text I would like to see in a different shape.</div>
<div id="demo2">Here is some text I would like to see in a different shape.</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="http://circletype.labwire.ca/js/circletype.js"></script>
<script src="http://tympanus.net/Development/Arctext/js/jquery.arctext.js"></script>
<script>
$("#demo1").click(function(){
$('#demo1').circleType({radius:384});
});
$("#demo2").click(function(){
$('#demo2').circleType({radius:384, dir:-1});
});
</script>

javascript forEach - add addEventListener on all buttons

I'm not so skilled with javascript so I'm looking for a little help.
I'm using a script found on Codrops (3D Grid Effect - http://tympanus.net/Development/3DGridEffect/).
All is working fine as expected but I'm trying to "modify" it for my needs.
Basically, I want to trigger the "effect" NOT clicking on the whole container but on a button placed inside it.
The structure I'm using is:
<section class="grid3d vertical" id="grid3d">
<div class="grid-wrap">
<div class="grid">
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
</div>
</div>
<div class="content">
<div>
<div class="dummy-img"></div>
<p class="dummy-text">Some text</p>
<p class="dummy-text">Some more text</p>
</div>
<div>
<!-- ... -->
</div>
<!-- ... -->
<span class="loading"></span>
<span class="icon close-content"></span>
</div>
</section>
<script>
new grid3D( document.getElementById( 'grid3d' ) );
</script>
And the script (js) is
/**
* grid3d.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2014, Codrops
* http://www.codrops.com
*/
;( function( window ) {
'use strict';
function grid3D( el, options ) {
this.el = el;
this.options = extend( {}, this.options );
extend( this.options, options );
this._init();
}
// any options you might want to configure
grid3D.prototype.options = {};
grid3D.prototype._init = function() {
// grid wrapper
this.gridWrap = this.el.querySelector( 'div.grid-wrap' );
// grid element
this.grid = this.gridWrap.querySelector( 'div.grid' );
// main grid items
this.gridItems = [].slice.call( this.grid.children );
// default sizes for grid items
this.itemSize = { width : this.gridItems[0].offsetWidth, height : this.gridItems[0].offsetHeight };
// content
this.contentEl = this.el.querySelector( 'div.content' );
// content items
this.contentItems = [].slice.call( this.contentEl.children );
// close content cross
this.close = this.contentEl.querySelector( 'span.close-content' );
// loading indicator
this.loader = this.contentEl.querySelector( 'span.loading' );
// support: support for pointer events, transitions and 3d transforms
this.support = support.pointerevents && support.csstransitions && support.csstransforms3d;
// init events
this._initEvents();
};
grid3D.prototype._initEvents = function() {
var self = this;
// open the content element when clicking on the main grid items
this.gridItems.forEach( function( item, idx ) {
item.addEventListener( 'click', function() {
self._showContent( idx );
} );
} );
// close the content element
this.close.addEventListener( 'click', function() {
self._hideContent();
} );
if( this.support ) {
// window resize
window.addEventListener( 'resize', function() { self._resizeHandler(); } );
// trick to prevent scrolling when animation is running (opening only)
// this prevents that the back of the placeholder does not stay positioned in a wrong way
window.addEventListener( 'scroll', function() {
if ( self.isAnimating ) {
window.scrollTo( self.scrollPosition ? self.scrollPosition.x : 0, self.scrollPosition ? self.scrollPosition.y : 0 );
}
else {
self.scrollPosition = { x : window.pageXOffset || docElem.scrollLeft, y : window.pageYOffset || docElem.scrollTop };
// change the grid perspective origin as we scroll the page
self._scrollHandler();
}
});
}
};
// creates placeholder and animates it to fullscreen
// in the end of the animation the content is shown
// a loading indicator will appear for 1 second to simulate a loading period
grid3D.prototype._showContent = function( pos ) {
if( this.isAnimating ) {
return false;
}
this.isAnimating = true;
var self = this,
loadContent = function() {
// simulating loading...
setTimeout( function() {
// hide loader
classie.removeClass( self.loader, 'show' );
// in the end of the transition set class "show" to respective content item
classie.addClass( self.contentItems[ pos ], 'show' );
}, 1000 );
// show content area
classie.addClass( self.contentEl, 'show' );
// show loader
classie.addClass( self.loader, 'show' );
classie.addClass( document.body, 'noscroll' );
self.isAnimating = false;
};
// if no support just load the content (simple fallback - no animation at all)
if( !this.support ) {
loadContent();
return false;
}
var currentItem = this.gridItems[ pos ],
itemContent = currentItem.innerHTML;
// create the placeholder
this.placeholder = this._createPlaceholder(itemContent );
// set the top and left of the placeholder to the top and left of the clicked grid item (relative to the grid)
this.placeholder.style.left = currentItem.offsetLeft + 'px';
this.placeholder.style.top = currentItem.offsetTop + 'px';
// append placeholder to the grid
this.grid.appendChild( this.placeholder );
// and animate it
var animFn = function() {
// give class "active" to current grid item (hides it)
classie.addClass( currentItem, 'active' );
// add class "view-full" to the grid-wrap
classie.addClass( self.gridWrap, 'view-full' );
// set width/height/left/top of placeholder
self._resizePlaceholder();
var onEndTransitionFn = function( ev ) {
if( ev.propertyName.indexOf( 'transform' ) === -1 ) return false;
this.removeEventListener( transEndEventName, onEndTransitionFn );
loadContent();
};
self.placeholder.addEventListener( transEndEventName, onEndTransitionFn );
};
setTimeout( animFn, 25 );
};
grid3D.prototype._hideContent = function() {
var self = this,
contentItem = this.el.querySelector( 'div.content > .show' ),
currentItem = this.gridItems[ this.contentItems.indexOf( contentItem ) ];
classie.removeClass( contentItem, 'show' );
classie.removeClass( this.contentEl, 'show' );
// without the timeout there seems to be some problem in firefox
setTimeout( function() { classie.removeClass( document.body, 'noscroll' ); }, 25 );
// that's it for no support..
if( !this.support ) return false;
classie.removeClass( this.gridWrap, 'view-full' );
// reset placeholder style values
this.placeholder.style.left = currentItem.offsetLeft + 'px';
this.placeholder.style.top = currentItem.offsetTop + 'px';
this.placeholder.style.width = this.itemSize.width + 'px';
this.placeholder.style.height = this.itemSize.height + 'px';
var onEndPlaceholderTransFn = function( ev ) {
this.removeEventListener( transEndEventName, onEndPlaceholderTransFn );
// remove placeholder from grid
self.placeholder.parentNode.removeChild( self.placeholder );
// show grid item again
classie.removeClass( currentItem, 'active' );
};
this.placeholder.addEventListener( transEndEventName, onEndPlaceholderTransFn );
}
// function to create the placeholder
/*
<div class="placeholder">
<div class="front">[content]</div>
<div class="back"></div>
</div>
*/
grid3D.prototype._createPlaceholder = function( content ) {
var front = document.createElement( 'div' );
front.className = 'front';
front.innerHTML = content;
var back = document.createElement( 'div' );
back.className = 'back';
back.innerHTML = ' ';
var placeholder = document.createElement( 'div' );
placeholder.className = 'placeholder';
placeholder.appendChild( front );
placeholder.appendChild( back );
return placeholder;
};
grid3D.prototype._scrollHandler = function() {
var self = this;
if( !this.didScroll ) {
this.didScroll = true;
setTimeout( function() { self._scrollPage(); }, 60 );
}
};
// changes the grid perspective origin as we scroll the page
grid3D.prototype._scrollPage = function() {
var perspY = scrollY() + getViewportH() / 2;
this.gridWrap.style.WebkitPerspectiveOrigin = '50% ' + perspY + 'px';
this.gridWrap.style.MozPerspectiveOrigin = '50% ' + perspY + 'px';
this.gridWrap.style.perspectiveOrigin = '50% ' + perspY + 'px';
this.didScroll = false;
};
grid3D.prototype._resizeHandler = function() {
var self = this;
function delayed() {
self._resizePlaceholder();
self._scrollPage();
self._resizeTimeout = null;
}
if ( this._resizeTimeout ) {
clearTimeout( this._resizeTimeout );
}
this._resizeTimeout = setTimeout( delayed, 50 );
}
grid3D.prototype._resizePlaceholder = function() {
// need to recalculate all these values as the size of the window changes
this.itemSize = { width : this.gridItems[0].offsetWidth, height : this.gridItems[0].offsetHeight };
if( this.placeholder ) {
// set the placeholders top to "0 - grid offsetTop" and left to "0 - grid offsetLeft"
this.placeholder.style.left = Number( -1 * ( this.grid.offsetLeft - scrollX() ) ) + 'px';
this.placeholder.style.top = Number( -1 * ( this.grid.offsetTop - scrollY() ) ) + 'px';
// set the placeholders width to windows width and height to windows height
this.placeholder.style.width = getViewportW() + 'px';
this.placeholder.style.height = getViewportH() + 'px';
}
}
// add to global namespace
window.grid3D = grid3D;
})( window );
Now, I'm aware that the "crucial" portion of the code where I have to look is:
// open the content element when clicking on the main grid items
this.gridItems.forEach( function(item, idx ) {
item.addEventListener( 'click', function() {
item._showContent( idx ); } ); } );
So, my question again: how to trigger the event when the div (button) class "click-me" is clicked on every "boxes"?
Thanks to all in advance (i'm struggling with it for hours...)
Have a look at the example here,
http://jsfiddle.net/y0mbn94n/
I have added some intialisation to get your particular classes
// get grid buttons and then make an iterable array out of them
this.gridButtons = this.el.querySelectorAll('button.btn-click-me');
this.gridButtonItems = [].slice.call(this.gridButtons);
and changed the function which iterates and adds a listener.
// open the content element when clicking on the buttonsItems
this.gridButtonItems.forEach(function (item, idx) {
item.addEventListener('click', function () {
self._showContent(idx);
});
});
If you want to call a callback function when the user clicks on a button:
var buttons = document.querySelectorAll('.btn-click-me');
for (var i = 0; i < buttons.length; i++) {
var self = buttons[i];
self.addEventListener('click', function (event) {
// prevent browser's default action
event.preventDefault();
// call your awesome function here
MyAwesomeFunction(this); // 'this' refers to the current button on for loop
}, false);
}
with the structure given
<div class="grid-wrap">
<div class="grid">
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
<div class="box"><div class="btn-click-me">Click to Show</div></div>
</div>
</div>
you just have to change the line you've said to:
item.children[0].addEventListener( 'click', function() {
as the btn-click-me would be the first child of each item.
If you would like a more generic solution you could use:
item.getElementsByClassName('btn-click-me')[0].addEventListener( 'click', function() {
where bnt-click-me would be the class of the button that you would want to bind the click event. Notice that [0] so you can select the very first item of the array, as getElementsByClassName will return one, even if there's only one element.
But if you say you're just starting with javascript y really recommend you using jQuery, it's selectors are much easier than vanilla javascript.

Why does my progress bar shows full progress value before it start loading

I made a progress bar using jQuery UI. here is the link to see it: DEMO
It works well, just there is a problem. At the code I have setTimeout( progress, 2000 ); which means it has to wait 2 seconds before it stars. But during this time it shows the background of .ui-progressbar-value which must be visible when the whole progress is completed. After 2 seconds it hides and to progress stars as normal.
Interestingly when I tried it on JSFiddle, it did not show this class and worked perfectly. So in browsers only have this problem. Here is the JSFiddel link
and this is my js code:
$(function() {
var progressbar = $( "#progressbar" ),
progressLabel = $( ".progress-label" );
progressbar.progressbar({
value: false,
change: function() {
progressLabel.text( progressbar.progressbar( "value" ) + "%" );
},
complete: function() {
progressLabel.text( "100%" );
$(".loader").delay(1000).fadeOut(750);
}
});
function progress() {
var val = progressbar.progressbar( "value" ) || 0;
progressbar.progressbar( "value", val + 1 );
if ( val < 100 ) {
setTimeout( progress, 100 );
}
}
setTimeout( progress, 2000 );
});
And CSS:
.enterance{
position:absolute;
overflow:hidden;
left:0;
top:0;
background-color:black;
width:100%;
height:100%;
z-index:10;
color:rgba(255,255,255,1.00);
}
.enterance .loader{
position:absolute;
width:600px;
height:500px;
top:50%;
left:50%;
margin:-250px 0 0 -300px;
}
.ui-progressbar-value {
background:url(http://goo.gl/V9dAfn) no-repeat;
width:600px;
height:429px;
border:0;
}
.ui-progressbar{
background:url(http://goo.gl/rBH0N1) no-repeat;
background-size:cover;
width:600px;
height:429px;
border:0;
}
.ui-progressbar .ui-progressbar-value{margin:0;}
.progress-label{
font-size:90px;
font-family: 'News Cycle', sans-serif;
color:#FFFFFF;
right:0px;
position:absolute;
}
So how can I NOT show this .ui-progressbar-value while it's waiting for 2 seconds? And Additionally, how can I add a fadeIn effect to this? like when page loads the image fades in ?
Thanks in advance.
Try this (can't be sure unless you had a fiddle of the issue):
$(function() {
var progressbar = $( "#progressbar" ),
progressLabel = $( ".progress-label" );
progressbar.progressbar({
value: false,
change: function() {
progressLabel.text( progressbar.progressbar( "value" ) + "%" );
},
complete: function() {
progressLabel.text( "100%" );
$(".loader").delay(1000).fadeOut(750);
}
});
function progress() {
var val = progressbar.progressbar( "value" ) || 0;
progressbar.progressbar( "value", val + 1 );
if ( val < 100 ) {
setTimeout( progress, 100 );
}
}
progressbar.progressbar( "value", 0 );
setTimeout( progress, 2000 );
});
Try removing the "$(function()" and running just the plain code?
var progressbar = $( "#progressbar" ),
progressLabel = $( ".progress-label" );
progressbar.progressbar({
value: false,
change: function() {
progressLabel.text( progressbar.progressbar( "value" ) + "%" );
},
complete: function() {
progressLabel.text( "100%" );
$(".loader").delay(1000).fadeOut(750);
}
});
function progress() {
var val = progressbar.progressbar( "value" ) || 0;
progressbar.progressbar( "value", val + 1 );
if ( val < 100 ) {
setTimeout( progress, 100 );
}
}
setTimeout( progress, 2000 );
Cant really work on it cuz it doesnt affect the fiddle right?

Keep hover inside containing div

I'm working on a treemap with d3.js and I need help to code some JS to change the hover behavior so that it doesn't overflow outside a containing div#graphic-treemap.
Simplifying the HTML structure, it looks like this:
<div id="graphics">
<div class="treemap">
<div id="graphic-treemap">
<div class="node">
<a href="#">
<span class="name">Name</span>
<strong class="value">R$ 3 Bi</strong>
<span class="more-info">
<span class="name-inside">Name</span>
<span class="year-and-amount">R$ 3 Bi</span>
<span class="percent">15% valor total do orçamento</span>
</span>
</a>
</div>
</div>
</div>
</div>
This is part of the CSS to clarify the hover thing:
#graphics .treemap .node a .more-info {
display: none;
position: absolute;
top: 20%;
left: 15%;
background-color: #FFF;
padding: 10px 20px;
text-align: center;
box-shadow: 1px 1px 2px #444;
z-index: 10;
}
#graphics .treemap .node a:hover .more-info {
display: block;
}
The final output of the treemap looks like this:
http://jsfiddle.net/tatianeps/GYsEa/
See that on the bottom right corner when the mouse is over some div.node without text inside the span.more-info inside that node overflows the div#graphic-treemap.
Below the JS that generates the treemap and some code I've been working on without success.
I was trying something with the function adjustHoverPosition at the end of the code. Also with node.on('mouseover',function(d){ });, but removed the code inside it because it didn't work either.
Any help will be appreciated.
var graphics =
{
debug: true,
init: function() {
graphics.load();
},
load: function() {
if ( typeof graphics_at_page != 'undefined' ) {
if ( typeof graphics_at_page[ 'map' ] != 'undefined' ) {
graphics.map.init( graphics_at_page[ 'map' ], 0 );
}
if ( typeof graphics_at_page[ 'treemap' ] != 'undefined' ) {
graphics.treemap.init( graphics_at_page[ 'treemap' ] );
}
if ( typeof graphics_at_page[ 'bar' ] != 'undefined' ) {
graphics.bar.init( graphics_at_page[ 'bar' ], 0 );
}
}
},
load_script: function( url, callback )
{
$.getScript( url, callback );
},
load_json: function( url, callback )
{
$.get(
url,
'json',
function(data) {
callback( data );
}
);
},
log: function( object ) {
if ( graphics.debug ) console.log( object );
},
treemap:
{
url: [],
data: [],
started: false,
title: 'title',
init: function( url ) {
graphics.treemap.url = url;
graphics.treemap.load();
},
load: function() {
if ( typeof d3 != 'undefined' ) {
graphics.treemap.create();
} else {
if ( typeof d3 === 'undefined' ) {
graphics.load_script( 'js/d3.min.js', graphics.treemap.create );
}
}
},
create: function() {
if ( typeof d3 === 'undefined' || graphics.treemap.started ) {
return false;
} else {
graphics.treemap.started = true;
}
$( '#graphics .treemap' ).prepend( '<div id="graphic-treemap"></div>' );
addLoader($('#graphics .treemap'));
graphics.treemap.graphic = d3.layout.treemap().size([665, 445]).sort(function(a,b) { return a.size - b.size; }).sticky(true).value( function( d ){ return d.size; });
graphics.treemap.div = d3.select( '#graphics .treemap #graphic-treemap' );
d3.json (
graphics.treemap.url[ 0 ],
function( error, root ) {
var node = graphics.treemap.div.datum( root ).selectAll( '.node' )
.data( graphics.treemap.graphic.nodes )
.enter().append( 'div' )
.attr( 'class', 'node' )
.call( graphics.treemap.position )
.style( 'background', function( d ) { return d.color; } )
.html( function( d ) {
return '<a href="' + d.link + '"><span class="name">' + d.name + '</span>' +
'<strong class="value" style="' + ( graphics.treemap.adjustFontSize(d.size) ) + '">' + d.amount + '</strong>' +
'<span class="more-info" style="border:8px solid '+ d.color +';">' +
'<span class="name-inside" style="color:'+ d.color +';">' + d.name + '</span>' +
'<span class="year-and-amount">' + d.totalAmount + '</span>' +
'<span class="percent">' + d.percent + ' valor total do orçamento' + '</span>' +
'</span>' +
'</a>';
})
.call( graphics.treemap.adjustTreemapText )
.call( graphics.treemap.adjustHoverPosition );
/*node.on('mouseover',function(d){
});*/
removeLoader($('#graphics .treemap'));
});
},
position: function() {
this.style( 'left', function(d) { return d.x + "px"; })
.style( 'top', function(d) { return d.y + "px"; })
.style( 'width', function(d) { return d.dx + "px"; })
.style( 'height', function(d) { return d.dy + "px"; });
},
adjustFontSize: function(size){
if(size < 1){ return ' display:none;'; }
else if(size>=1 && size <=12){ return ' font-size:24px;'; }
else if(size> 12 && size <=50) { return ' font-size:'+ size*2 +'px;'; }
else if(size> 50 && size <=100) { return ' font-size:'+ size*1.5 +'px;'; }
else return ' font-size:150px;';
},
adjustTreemapText: function(){
$('.treemap .node').each(function(){
if($(this).width() == 0) { $(this).attr('style','display:none;'); }
});
$('.treemap .node a .name, .treemap .node a .value').each(function(){
var thisHeight = $(this).height()+20;
var thisParentHeight = $(this).parents('a').innerHeight();
if(thisHeight >= thisParentHeight){ $(this).attr('style','display:none;'); }
});
$('.treemap .node a .name').each(function(){
var text = $(this).text();
$(this).append('<em class="temporary" style="display:inline;">'+text+'<em/>');
var thisHeight = $(this).height()+30;
var thisParentHeight = $(this).parents('a').innerHeight();
if(thisHeight >= thisParentHeight){
var temporaryWidth = $(this).find('.temporary').width()+10;
var thisParentWidth = $(this).parents('a').innerWidth();
if(temporaryWidth >= thisParentWidth){ $(this).attr('style','display:none;'); }
}
$(this).find('.temporary').remove();
});
},
adjustHoverPosition: function(){
$('.treemap .node').each(function(index){
if(index > 0){
var leftStr = $(this).css('left');
var left = parseInt(leftStr.replace('px',''));
var topStr = $(this).css('top');
var top = parseInt(topStr.replace('px',''));
if(left > 332) { $(this).find('.more-info').css('left','').css({right:'15%'}); }
if(top > 222) { $(this).find('.more-info').css('top','').css({bottom:'20%'}); }
}
});
}
}
};
function addLoader(loaderContainer) {
loaderContainer.prepend('<div class="loader"><span class="loading"></span></div>');
}
function removeLoader(loaderContainer) {
loaderContainer.find('.loader').remove();
}
$(document).ready(
function() {
graphics.init();
}
);
Edit:
I'm trying to use jQuery UI .position(), but it doesn't seem to work.
adjustHoverPosition: function(){
$('.treemap .node a span.more-info').position({
collision: "flip",
within: "#graphic-treemap"
});
}

Nonworking function as soon as page loading

There is a Youtube chromeless Javascript player in demo. Unless user clicks playlist pictures below player, title and time don't shown. To show title and time user has to click some playlist image or has to wait cahanging to the next video. I want title and time to be written without clicking anything after first video autoload. There might be a problem javascript function order. Nothing comes to my mind apart from this.
All codes are below to help next people in future
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" lang="en"/>
<title>title</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2/swfobject.js"></script>
</head>
<body>
<div class="ikinciSol">
Play
-
Pause
-
Stop
<div id="videoTime">
<span id="videoCurrentTime"></span>
<span id="videoDuration"></span>
</div>
<div id="ytplayer_status"></div>
<a name="ytplayer"></a>
<div id="ytplayer">You need Flash player 10+ and JavaScript enabled to view this video.</div>
<div id="ytplayer_div2"></div>
<script type="text/javascript">
//
// YouTube JavaScript API Player With Playlist
// http://911-need-code-help.blogspot.com/2009/10/youtube-javascript-player-with-playlist.html
// Revision 2 [2012-03-24]
//
// Prerequisites
// 1) Create following elements in your HTML:
// -- a) ytplayer: a named anchor
// -- b) ytplayer_div1: placeholder div for YouTube JavaScript Player
// -- c) ytplayer_div2: container div for playlist
// 2) Include SWFObject library from http://code.google.com/p/swfobject/
//
// Variables
// -- ytplayer_playlist: an array containing YouTube Video IDs
// -- ytplayer_playitem: index of the video to be played at any given time
//
var ytplayer_playlist = [ ];
var ytplayer_playitem = 0;
swfobject.addLoadEvent( ytplayer_render_player );
swfobject.addLoadEvent( ytplayer_render_playlist );
function ytplayer_render_player( )
{
swfobject.embedSWF
(
'http://www.youtube.com/apiplayer?video_id='+ ytplayer_playlist[ ytplayer_playitem ].videoid + '&enablejsapi=1&autoplay=1&loop=1&version=3&rel=0&fs=1&playerapiid=ytplayer',
'ytplayer',
'400',
'225',
'10',
null,
null,
{
allowScriptAccess: 'always',
allowFullScreen: 'true'
},
{
id: 'ytplayer'
}
);
}
// Update a particular HTML element with a new value
function updateHTML(elmId, value) {
var elem = document.getElementById(elmId);
if(typeof elem !== 'undefined' && elem !== null) {
document.getElementById(elmId).innerHTML = value;
}
}
//Converting seconds minute:second
function secondsToHms(d) {
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
return ((h > 0 ? h + ":" : "") + (m > 0 ? (h > 0 && m < 10 ? "0" : "") + m + ":" : "0:") + (s < 10 ? "0" : "") + s); }
// Display information about the current state of the player
function updatePlayerInfo() {
// Also check that at least one function exists since when IE unloads the
// page, it will destroy the SWF before clearing the interval.
if(ytplayer && ytplayer.getDuration) {
updateHTML("videoCurrentTime", secondsToHms(ytplayer.getCurrentTime())+' /');
updateHTML("videoDuration", secondsToHms(ytplayer.getDuration()));
updateHTML("bytesTotal", ytplayer.getVideoBytesTotal());
updateHTML("startBytes", ytplayer.getVideoStartBytes());
updateHTML("bytesLoaded", ytplayer.getVideoBytesLoaded());
updateHTML("volume", ytplayer.getVolume());
}
}
function ytplayer_render_playlist( )
{
for ( var i = 0; i < ytplayer_playlist.length; i++ )
{
var img = document.createElement( "img" );
img.src = "http://img.youtube.com/vi/" + ytplayer_playlist[ i ].videoid + "/default.jpg";
var a = document.createElement( "a" );
a.href = "#ytplayer";
//
// Thanks to some nice people who answered this question:
// http://stackoverflow.com/questions/1552941/variables-in-anonymous-functions-can-someone-explain-the-following
//
a.onclick = (
function( j )
{
return function( )
{
ytplayer_playitem = j;
ytplayer_playlazy( 1000 );
};
}
)( i );
a.appendChild( img );
document.getElementById( "ytplayer_div2" ).appendChild( a );
}
}
function ytplayer_playlazy( delay )
{
//
// Thanks to the anonymous person posted this tip:
// http://www.tipstrs.com/tip/1084/Static-variables-in-Javascript
//
if ( typeof ytplayer_playlazy.timeoutid != 'undefined' )
{
window.clearTimeout( ytplayer_playlazy.timeoutid );
}
ytplayer_playlazy.timeoutid = window.setTimeout( ytplayer_play, delay );
}
function ytplayer_play( )
{
var o = document.getElementById( 'ytplayer' );
if ( o )
{
o.loadVideoById( ytplayer_playlist[ ytplayer_playitem ].videoid );
document.getElementById( "ytplayer_status" ).innerHTML = ytplayer_playlist[ ytplayer_playitem ].title;
setInterval(updatePlayerInfo, 250);
}
}
//
// Ready Handler (this function is called automatically by YouTube JavaScript Player when it is ready)
// * Sets up handler for other events
//
function onYouTubePlayerReady( playerid )
{
var o = document.getElementById( 'ytplayer' );
if ( o )
{
o.addEventListener( "onStateChange", "ytplayerOnStateChange" );
o.addEventListener( "onError", "ytplayerOnError" );
}
}
//
// State Change Handler
// * Sets up the video index variable
// * Calls the lazy play function
//
function ytplayerOnStateChange( state )
{
if ( state == 0 )
{
ytplayer_playitem += 1;
ytplayer_playitem %= ytplayer_playlist.length;
ytplayer_playlazy( 1000 );
}
}
//
// Error Handler
// * Sets up the video index variable
// * Calls the lazy play function
//
function ytplayerOnError( error )
{
if ( error )
{
ytplayer_playitem += 1;
ytplayer_playitem %= ytplayer_playlist.length;
ytplayer_playlazy( 1000 );
}
}
//
// Add items to the playlist one-by-one
//
ytplayer_playlist.push(
{
videoid: 'tGvHNNOLnCk',
title: 'title1'
}
);
ytplayer_playlist.push(
{
videoid: '_-8IufkbuD0',
title: 'title2'
}
);
ytplayer_playlist.push(
{
videoid: 'wvsboPUjrGc',
title: "title3"
}
);
ytplayer_playlist.push(
{
videoid: '8To-6VIJZRE',
title: 'title4'
}
);
ytplayer_playlist.push(
{
videoid: '8pdkEJ0nFBg',
title: 'title5'
}
);
function play() {
if (ytplayer) {
document.getElementById('ytplayer').playVideo();
}
}
function pause() {
if (ytplayer) {
document.getElementById('ytplayer').pauseVideo();
}
}
function stop() {
if (ytplayer) {
document.getElementById('ytplayer').stopVideo();
}
}
</script>
</body>
</html>
Why you don't include :
document.getElementById( "ytplayer_status" ).innerHTML = ytplayer_playlist[ ytplayer_playitem ].title;
in your update function like shown below, the changes I have done are :
I added the set title function to the update function.
I added the setTimeout update function to body onload event
Take out the set title and timeout from ytplayer_play
Here is the correction :
http://jsfiddle.net/KpTaA/1/

Categories