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/
Related
I'm using a script to work a timer so I can track time on projects. This script currently doesn't start until I click start, which is perfect for starting to track a project but if I've started a project and either closed the browser or closed the page, when I come back to the page, I need to be able to set the starting seconds and have it running when the page loads. I know how to set the seconds to start at but I don't know what to change in the script via PHP to have the timer running and the start/stop button set to "stop".
In short, I'd like a flag I can change via PHP that would toggle this script between the proper status of the start/stop button and starting the timer on pageload or starting it on click of the start/stop button.
(function(d) {
'use strict';
var seconds = 0, si, h0, m0, s0, flag = true;
var timer = d.getElementById( 'tiles' ),
start = d.getElementById( 'start' ),
reset = d.getElementById( 'reset' );
timer.innerHTML = '<span>00</span><span>00</span><span>00</span>';
start.addEventListener('click',
function() {
if ( flag === true ) {
seconds ++;
si = setInterval(
function(){
h0 = pad( parseInt( seconds / 3600 ) );
m0 = pad( parseInt( seconds / 60 % 60 ) );
s0 = pad( seconds % 60 );
timer.innerHTML = '<span>' + h0 + '</span><span>' + m0 + '</span><span>' + s0 + '</span>';
seconds ++;
}, 1000 );
start.textContent = 'stop';
flag = false;
}
else {
clearInterval(si);
start.textContent = 'start';
flag = true;
}}, false );
reset.addEventListener('click',
function() {
clearInterval( si );
start.textContent = 'start';
flag = true;
timer.innerHTML = '<span>00</span><span>00</span><span>00</span>';
seconds = 0;
}, false );
function pad( n ) {
return ( n < 10 ? '0' : '' ) + n;
}
}(document));
I believe it's enough for you just to change
start.addEventListener('click'...)
to
start.addEventListener('load'...)
Here's MDN Docs - https://developer.mozilla.org/en-US/docs/Web/Events/load
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.
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.
I'm trying to display a different image depending on the timer's result and can't find a way through. So far I have a start and stop button, but when I click stop, I want to use the value the timer is on and display an image(on alertbox or the webpage itself) depending on that value.
if( timer =>60){
img.src("pizzaburnt.jpg");
}elseif (timer <=30){
img.src("pizzaraw.jpg");
}
else{
img.src("pizzaperfect.jpg
}
///Time
var check = null;
function printDuration() {
if (check == null) {
var cnt = 0;
check = setInterval(function () {
cnt += 1;
document.getElementById("para").innerHTML = cnt;
}, 1000);
}
}
//Time stop
function stop() {
clearInterval(check);
check = null;
document.getElementById("para").innerHTML = '0';
}
**HTML**
<td>
Timer :<p id="para">0</p>
</td>
Any advice or dicussion would be great, thanks.
Something like this would work better and it's more compact:
var img = document.getElementById("image");
var imageSrcs = ['pizzaRaw.jpg', 'pizzaPerfect.jpg', 'pizzaBurnt.jpg'];
var imageIndex = 0;
var interval = setInterval(animate, 30000); //change image every 30s
var animate = function() {
//change image here
//using jQuery:
img.src(imageSrcs[imageIndex]);
imageIndex++; //move index for next image
if (imageIndex == imageSrcs.length) {
clearInterval(interval); //stop the animation, the pizza is burnt
}
}
animate();
Reason you wouldn't want to use an increment variable and a 1 second timer is because your just conflating your logic, spinning a timer, and making a bit of a mess when all you really want is the image to change every 30 seconds or whenever.
Hope this helps.
You need an <img> tag in your HTML like this:
<html>
<body>
Timer: <p id="para">0</p>
Image: <img id="image" />
</body>
</html>
And the Javascript code will be like:
var handle;
var timerValue = 0;
var img = document.getElementById( "image" );
var para = document.getElementById("para");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if ( timerValue >= 60 ) {
img.src( "pizzaburnt.jpg" );
}else if ( timer <= 30 ) {
img.src( "pizzaraw.jpg" );
} else {
img.src("pizzaperfect.jpg" );
}
}
function start () {
if ( handle ) {
stop();
}
timerValue = 0;
setInterval( onTimer, 1000 );
}
function stop () {
if ( handle ) {
clearInterval ( handle );
}
}
Please make sure that these 3 files are in the same directory as your HTML file:
pizzaburnt.jpg
pizzaraw.jpg
pizzaperfect.jpg
I'm using the following code (which has some Frog VLE API code in it; hopefully that's not too relevant) to pick a random student from a list.
This works well, but sometimes - given its random nature - it only runs for a very brief period of time. Would it be possible to loop this a number of times first, to ensure that it runs for X period of time as a minimum?
var Count = 0;
/* construct the array of people */
for (var i in data.users) {
for (var n = 0; n < data.users[i].Quantity; n++) {
var TempObj = { 'Count' : Count, 'Student_ID' : i, 'Student_Name' : data.users[i].Student_Name };
RewardPurchases.PurchasesArray[Count] = TempObj;
Count++;
}
}
... more code here, nothing relevant to the way the script works ...
$('button#random').click( function() {
/* first things first, play a drum-roll when the button is clicked! */
$('embed').remove();
$('body').append('<embed src="/user/74/177499.wav" autostart="true" hidden="true" loop="true">');
/* take the RewardPurchases.PurchasesArray and sort it so that there's no particular order */
RewardPurchases.PurchasesArray.sort(function() {return 0.5 - Math.random()})
/* remove the winner class for consecutive re-rolls */
$display.removeClass( "winner" );
$display.addClass( "spinner" );
/* determine the number of people in the array and calculate a random winner */
var total = RewardPurchases.PurchasesArray.length,
selected = Math.floor( Math.random() * total ),
i = 0;
/* work out how long each name should appear for, dependent upon how many people are in the array */
var timeout = ( 15000 / total );
/* run through the array of people ... */
for (i=0; i<total; i++) {
setTimeout((function(i){
return function(){
console.log( "timeout", i );
/* ... if the person in the array is a valid person! then display their name */
if (typeof RewardPurchases.PurchasesArray[i] === 'object' && typeof RewardPurchases.PurchasesArray[i] !== null) {
$display.text( "[" + RewardPurchases.PurchasesArray[i].Count + "] " + RewardPurchases.PurchasesArray[i].Student_Name.toUpperCase() );
/* if we encounter the winner, play a cheering wav and change the class of the display so that they appear in big, bold, red text */
if( i === selected ) {
$('embed').remove();
$('body').append('<embed src="/user/74/177086.wav" autostart="true" hidden="true" loop="false">');
$display.addClass( "winner" );
}
}
};
}(i)), i*timeout);
/* if the winner has been found, break the loop */
if( i === selected ) {
break;
}
}
} );
Thanks in advance,
You could do something like this :
function doforsec(msec, func) {
var curDate = new Date().getTime();
while ((new Date().getTime() - curDate) < msec) {
func();
}
}
doforsec(200, function() {
console.log(new Date().getSeconds())
});
This executes the function given to doforsec again and again until the timeperiod specified (in milliseconds) is over. (first i had seconds, but i think milliseconds will be better)
JSfiddle
Because my deadline for this is.. well, around 8 hours from posting this.. I've decided to re-write the script and use a jQuery plugin:
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
$(document).ready(function(){
var staff = [ 'hardcoded', 'list', 'of', 'staff', 'members' ];
$('button#start').click( function() {
var $display = $('#display'),
$results = $('#results table');
$display.removeClass( "winner" );
$display.addClass( "spinner" );
var counter = 0,
rand = 0,
run_time = 10,
delay = ( run_time * 100 ) / staff.length,
loop_number = 5,
max_count = staff.length * loop_number;
$display.doTimeout( 'loop', delay, function() {
counter++;
var newRand = Math.floor( Math.random() * staff.length );
if ( rand === newRand ) {
rand = Math.floor( Math.random() * staff.length );
} else {
rand = newRand;
}
$(this).text( staff[rand] );
if ( counter < max_count ) { return true; }
else {
$('#results tr:last').after('<tr><td class="number">' + staff.length + '</td><td>' + staff[rand] + '</td></tr>');
staff.remove( rand );
}
});
$display.doTimeout( 'class', max_count * delay, function() {
$display.removeClass( "spinner" );
$display.addClass( "winner" );
});
});
});
After var timeout = ( 15000 / total ); insert the following, and remove the line for (i=0; i
var totalTime = 2000;
var timeOut= Math.Ceiling(totalTime/timeout);
var timesToDisplay = totalTime / timeOut;
var currentDisplay = 0;
for (currentDisplay = 0; currentDisplay < timesToDisplay; currentDisplay++) {
i = currentDisplay % total;