I have articles to display in an application of smart TV (coding JavaScript) but unfortunately, it shows only the first few onces while all the rest of them stay down hidden. Is there any way how to scroll in Samsung Smart TV ?
if you are using divs or list to display data than you can easily hide a list or Div using jquery on key press.
scrollBy and scrollTo work fine on samsung smart tv (not on lg). You did not describe your problem well enough, but I guess all you need to bind up/down keys to one of the scroll APIs.
I recommend using isscrolljs instead of using scrollBy and scrollTo, as it works well on both samsung and lg. smarttvjs also uses it.
var widgetAPI = new Common.API.Widget();
var tvKey = new Common.API.TVKeyValue();
var InitH = 440 -10;
var InitTop = 50;
var MaxTop;
var interT = null, interD = null;
var d;
var t;
var prevT = null;
var Main =
{
};
Main.onLoad = function()
{
// Enable key event processing
this.enableKeys();
widgetAPI.sendReadyEvent();
MaxTop = $("#Content").position().top - (parseInt($("#Content").css("height"))- InitH);
alert($("#Content").position().top);
alert(MaxTop);
};
Main.onUnload = function()
{
};
Main.enableKeys = function()
{
document.getElementById("anchor").focus();
};
Main.keyDown = function()
{
var keyCode = event.keyCode;
alert("Key pressed: " + keyCode);
switch(keyCode)
{
case tvKey.KEY_RETURN:
case tvKey.KEY_PANEL_RETURN:
alert("RETURN");
widgetAPI.sendReturnEvent();
break;
case tvKey.KEY_LEFT:
alert("LEFT");
break;
case tvKey.KEY_RIGHT:
alert("RIGHT");
break;
case tvKey.KEY_UP:
alert("UP");
interTop();
d = new Date();
t =parseInt((d.getTime()%10000)/1000);
alert(t+" ---------" );
//alert(scroll);
//Math.abs(t-prevT)>=3 && Math.abs(t-prevT)<=7
if(($("#Content").position().top<InitTop && t!=prevT) || prevT == null){
$("#Content").css("top",$("#Content").position().top+50+"px");
prevT = t;
}else if($("#Content").position().top>InitTop){
$("#Content").css("top",InitTop+"px");
}
break;
case tvKey.KEY_DOWN:
alert("DOWN");
interDown();
d = new Date();
t =parseInt((d.getTime()%10000)/1000);
alert(t+" ---------" );
//alert(scroll);
//Math.abs(t-prevT)>=3 && Math.abs(t-prevT)<=7
if(($("#Content").position().top>MaxTop && t!=prevT) || prevT == null){
$("#Content").css("top",$("#Content").position().top-50+"px");
prevT = t;
}else if($("#Content").position().top<MaxTop){
$("#Content").css("top",MaxTop+"px");
}
break;
case tvKey.KEY_ENTER:
case tvKey.KEY_PANEL_ENTER:
alert("ENTER");
alert($("#Content").css("height"));
alert($("#Content").position().top);
break;
default:
alert("Unhandled key");
break;
}
};
function interTop(){
clearInterval(interD);
interD = null;
if(interT == null){
interT = setInterval(function(){if($("#Content").position().top>InitTop){
$("#Content").css("top",InitTop+"px");
}
},500);
}
}
function interDown(){
clearInterval(interT);
interT = null;
if(interD == null){
interD = setInterval(function(){if($("#Content").position().top<MaxTop){
$("#Content").css("top",MaxTop+"px");
}
},500);
}
}
var widgetAPI = new Common.API.Widget();
var tvKey = new Common.API.TVKeyValue();
var total_item = 3, current_item = 0;
//var variable = Document.getElementById("Content");
var Main =
{
};
Main.onLoad = function()
{
// Enable key event processing
this.enableKeys();
widgetAPI.sendReadyEvent();
navigation("DOWN");
fetchNews();
///////////////////////////////////
/* L'appel du Parser à compléter */
/* L'appel du Parser à compléter */
/* L'appel du Parser à compléter */
///////////////////////////////////
};
Main.onUnload = function()
{
};
Main.enableKeys = function()
{
document.getElementById("anchor").focus();
};
Main.keyDown = function()
{
var keyCode = event.keyCode;
alert("Key pressed: " + keyCode);
switch(keyCode)
{
case tvKey.KEY_RETURN:
case tvKey.KEY_PANEL_RETURN:
alert("RETURN");
widgetAPI.blockNavigation(event);
parent.location = "index.html";
break;
case tvKey.KEY_LEFT:
alert("LEFT");
break;
case tvKey.KEY_RIGHT:
alert("RIGHT");
break;
case tvKey.KEY_UP:
alert("UP");
//navigation("UP");
break;
case tvKey.KEY_DOWN:
alert("DOWN");
//navigation("DOWN");
break;
case tvKey.KEY_ENTER:
case tvKey.KEY_PANEL_ENTER:
alert("ENTER");
//gotoPage();
break;
default:
alert("Unhandled key");
break;
}
};
function navigation(direction){
$("#btn_"+current_item).removeClass("selected_btn");
if(direction == "UP"){
if(current_item == 1)
current_item = total_item;
else
current_item--;
}else if(direction == "DOWN"){
if(current_item == total_item)
current_item = 1;
else
current_item++;
}
$("#btn_"+current_item).addClass("selected_btn");
}
function gotoPage(){
switch(current_item){
//case 1: parent.location = "gallery.html"; break;
case 2: parent.location = "news.html"; break;
case 3: parent.location = "about.html"; break;
}
}
function fetchNews(){
if ( ParserNews.init()) {
ParserNews.dataReceivedCallback = function() {
prepareNewsList();
};
ParserNews.fetchDatas();
}
};
function prepareNewsList(){
var i;
for(i=0; i<DataNews.getCount(); i++){
$("<div/>").addClass("newsItem").html('<div class="title">'+DataNews.getTitle(i)+'</div></br><div><img src ="'+DataNews.getDate(i)+'"></div>').appendTo($("body"));
}
alert(DataNews.getTitle(3)) ;
alert(DataNews.getMiservices(3)) ;
alert(DataNews.getCount());
}
// This is the CSS file
* {
padding: 0;
margin: 0;
border: 0;
}
/* Layout */
body {
width: 1280px;
height: 720px;
background-image: url("../img/backk.jpg");
position: fixed;
}
.newsItem {
padding: 10px;
color: #fff;
width: 1250px;
height: 100px;
margin-bottom: 10px;
margin-left: 80px;
background-color: #388e8e;
}
.title {
color: #87d2ef;
font-size: 20px;
}
.description {
color: #fff;
font-size: 15px;
}
.img {
width: 50px;
height: 60px;
position: absolute;
left: 50px;
top: 50px;
}
.text {
position: absolute;
width: 500px;
height: 400px;
left: 400px;
top: 50px;
font-size: 25px;
color: #fff;
}
#Content {
-webkit-transition: top 1s ease-in-out;
}
.transitions .top {
top: 0;
}
.transitions .bottom {
top: -70px;
}
// Finally HTML file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Tunisie</title>
<!-- TODO : Common API -->
<script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/Widget.js"></script>
<script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/API/TVKeyValue.js"></script>
<script type="text/javascript" language="javascript" src="$MANAGER_WIDGET/Common/jquery.js"></script>
<!-- TODO : Javascript code -->
<script type="text/javascript" src="app/javascript/Parser_News.js"></script>
<script type="text/javascript" src="app/javascript/Data_News.js"></script>
<script language="javascript" type="text/javascript" src="app/javascript/News.js"></script>
<script language="javascript" type="text/javascript" src="app/javascript/testScroll.js"></script>
<!-- TODO : Style sheets code -->
<link rel="stylesheet" href="app/stylesheets/testScroll.css" type="text/css">
<!-- TODO: Plugins -->
</head>
<body onload="Main.onLoad();" onunload="Main.onUnload();">
<!-- Dummy anchor as focus for key events -->
<div class="newsItem" id="Content" style="width:100%; top:50px; left:100px; border:solid 1px #000000; position:fixed;">
</div>
</body>
</html>
Related
I have a simple app which I have three different videos, I want each video to play at certain time. As example:
First video to play.
between 5:00 AM and 10:00 AM.
Second video to play.
between 10:00 AM and 22:00 PM.
Third video to play.
between 22:00 PM and 5:00 AM.
So assume if a user visited my app around 9:00 AM. It should automatically play the first video. If the user visit around 11: 00 AM, the second video plays, and etc.
I want a function to run function at set interval only at certain time of the day using javascript and the postMessage function,
Here is my solution:
app.js
var welcomeMovie1 = "http://mirrors.standaloneinstaller.com/video-sample/jellyfish-25-mbps-hd-hevc.mp4";
var welcomeMovie2 = "http://mirrors.standaloneinstaller.com/video-sample/TRA3106.mp4"
var welcomeMovie3 = "http://mirrors.standaloneinstaller.com/video-sample/Panasonic_HDC_TM_700_P_50i.mp4";
var messageTime;
//function to play a video1 to iframe using post messages
function welcomeMessage1() {
document.getElementById('videoframe').contentWindow.postMessage(
JSON.stringify({
event: 'playVideo(welcomeMovie1)'
}),
'*'
)
}
//function to play a video2 to iframe using post messages
function welcomeMessage2() {
document.getElementById('videoframe').contentWindow.postMessage(
JSON.stringify({
event: 'playVideo(welcomeMovie2)'
}),
'*'
)
}
//function to play a video3 to iframe using post messages
function welcomeMessage3() {
document.getElementById('videoframe').contentWindow.postMessage(
JSON.stringify({
event: 'playVideo(welcomeMovie2)'
}),
'*'
)
}
//function to play a video1 to iframe using post messages at Specific time
setInterval(function() {
var messageTime = new Date().getHours();
if (messageTime >= 5 && messageTime < 10) {
welcomeMessage1();
console.log(welcomeMessage2());
}
}, 1000 * 60);
//function to play a video2 to iframe using post messages at Specific time
setInterval(function() {
var messageTime = new Date().getHours();
console.log(date.toLocaleString('en-GB'));
if (messageTime >= 10 && messageTime < 22) {
welcomeMessage2();
console.log(welcomeMessage2());
}
}, 1000 * 60);
//function to play a video3 to iframe using post messages at Specific time
setInterval(function() {
var messageTime = new Date().getHours();
if (messageTime >= 22 && messageTime < 5) {
welcomeMessage3();
}
}, 1000 * 60);
// promise function to create custom video controls and play functions
function playVideo(src) {
$("#playervideo").attr("src", src);
$("#playervideo")[0].muted = false;
if (autoplay == true) {
var playPromise = $("#playervideo")[0].play();
if (playPromise !== undefined) {
playPromise.then(function() {}).catch(function() {
if (autoplay == true) {
$("#video-unmute-button").addClass("show");
$("#playervideo")[0].muted = true;
var playPromise2 = $("#playervideo")[0].play();
playPromise2.then(function() {
}).catch(function() {
$("#video-start-button").addClass("show");
$("#video-start-button").on("click", function() {
$("#playervideo")[0].muted = false;
$("#playervideo")[0].play();
$("#video-start-button").removeClass("show");
});
});
console.log("pause force");
} else {
}
});
} else {}
} else {
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video Frame</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<iframe id="videoframe" src="videoframe.html"></iframe>
<br/>
<!-- <input id="name" type="text"/> -->
</body>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script src="js/app.js" type="text/javascript"></script>
<script src="js/form.js" type="text/javascript"></script>
</html>
Here is plunker for full demo: demo
Unfortunately it's not working,
What do I need to change in my code to get what I want?
<iframe> & <video>
Autoplay
Autoplay ain't what it used to be. There's too many restrictions and various criteria involved in getting a <video> tag to autoplay. Here's what was needed:
<video> tag needs [muted] and [autoplay] attributes
<video ... muted autoplay></video>
<iframe> tag needs [allow="autoplay"] attribute. Full screen is optional
<iframe ... allowfullscreen allow="autoplay; fullscreen"></iframe>
In the demo below loadVideo() is the function that loads a MP4 file to the <video> tag's [src] according to the current time. Autoloading media from an <iframe> is tricky because they are one of the last of the DOM content to load. It's best to run the function from the child page (videoframe.html) in an IIFE (Immediately-invoked Function Expression).
(function() {
loadVideo();
})();
Promises
In order to invoke play() method, you'll need to use the Promise API. This is another instance when something works and engineers want to overcomplicate it.
async function promisePlay() {
try {
await document.querySelector('video').play();
} catch (err) {
...
}
}
postMessage
For cross-domain communication using the postMessage API via <iframe>, the developer must have ownership of both domains. Ownership doesn't necessarily mean full administrative privileges, just enough so that both pages can actually be edited. There are some APIs that'll meet you halfway like YouTube and Vimeo as well.
Basically the parent page (index.html) will send a message:
window.frames[0].postMessage(data, origin);
window.frames[0] will get the first <iframe> and access it's window content, an equivalent to: document.querySelector('iframe').contentWindow;.
data is just a string.
origin is usually the location.protocol and location.hostname or location.origin of the parent page (index.html): https://www.example.com.
The child page (videoframe.html) receives the data (just a typical string) by listening for the message event on it's Window Object:
window.addEventListener("message", callback);
Most examples show how a message is sent and received, and the result of the message being displayed on the child page -- lame 🙄. Here's what a callback would look like if it were actually useful:
function callback(event) {
var string = event.data;
// Optional-------------------------
var from = event.origin;
if (from !== 'https://www.example.com') {
document.querySelector('#displayMsg').textContent = `MESSAGE REJECTED`;
return;
}
//----------------------------------
if (string === "play") {
promisePlay();
} else if (string === "pause") {
document.querySelector('video').pause();
} else if (string === "stop") {
document.querySelector('video').pause();
document.querySelector('video').currentTime = 0;
} else {
document.querySelector('#displayMsg').textContent = `ERROR: ${string} is not a command.`;
}
}
Plunker
Demo
index.html
Note: The following Stack Snippet does not function properly due to SO restriction on <iframe> use. For a fully functional demo go to this Plunker.
html,
body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
font: 400 16px/1.5 Consolas;
overflow: hidden;
}
main {
width: 100%;
height: auto;
padding: 10px;
}
section {
height: 0;
width: 100%;
position: relative;
padding-bottom: 56.25%;
margin: 15px auto 5px;
}
fieldset {
width: fit-content;
padding: 5px;
}
iframe {
height: 100%;
width: 100%;
overflow: hidden;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
select,
button {
font: inherit;
padding: 0 3px;
line-height: 1.2;
}
#msg {
position: absolute;
z-index: 1;
background: rgba(0, 0, 0, 0.5);
}
#time,
#rX {
display: block;
float: left;
color: gold;
padding: 0 5px;
width: 70px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video Frame</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<section>
<iframe src="https://run.plnkr.co/preview/cjpwrvczh00073a5v3m08unmw/videoframe.html" width='100%' height='100%' scrolling='no' frameborder='0' allowfullscreen allow="autoplay; fullscreen"></iframe>
</section>
<form id='control'>
<fieldset>
<select id='tX'>
<option value='Timeslot'>Select</option>
<optgroup label='Command'>
<option>Play</option>
<option>Pause</option>
<option>Stop</option>
</optgroup>
<optgroup label='Load Media'>
<option>Video 1</option>
<option>Video 2</option>
<option>Video 3</option>
</optgroup>
<optgroup label="Test">
<option>Messages</option>
<option>Controls</option>
</optgroup>
</select>
<button>Send</button>
</fieldset>
</form>
</main>
<script>
window.onload = function(e) {
var ctrl = document.forms.control;
var cX = ctrl.elements;
var tX = cX.tX;
ctrl.addEventListener('submit', function(e) {
e.preventDefault();
window.frames[0].postMessage(tX.value, "https://" + location.hostname);
console.log(tX.value);
});
};
</script>
</body>
</html>
videoframe.html
html,
body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
font: 400 16px/1.5 Consolas;
overflow: hidden;
}
main {
width: 100%;
height: auto;
padding: 10px;
}
section {
height: 0;
width: 100%;
position: relative;
padding-bottom: 56.25%;
margin: 15px auto 5px;
}
fieldset {
width: fit-content;
padding: 5px;
}
iframe {
height: 100%;
width: 100%;
overflow: hidden;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
select,
button {
font: inherit;
padding: 0 3px;
line-height: 1.2;
}
#msg {
position: absolute;
z-index: 1;
background: rgba(0, 0, 0, 0.5);
}
#time,
#rX {
display: block;
float: left;
color: gold;
padding: 0 5px;
width: 70px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Video iframe</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<aside id='msg'>
<output id='rX'></output>
<time id='time'></time>
</aside>
<video id='vX' src='about:blank' width='96%' muted autoplay></video>
<script>
var v = document.getElementById('vX');
var vid =
'https://storage04.dropshots.com/photos6000/photos/1381926/20170326/';
var r = document.getElementById('rX');
var t = document.getElementById('time');
(function() {
loadVideo();
})();
window.addEventListener("message", rXMsg);
function rXMsg(e) {
var msg = e.data;
switch (msg) {
case 'Play':
playMedia();
break;
case 'Pause':
v.pause();
break;
case 'Stop':
v.pause();
v.currentTime = 0;
break;
case 'Video 1':
v.src = vid + '005609.mp4';
v.load();
break;
case 'Video 2':
v.src = vid + '005610.mp4';
v.load();
break;
case 'Video 3':
v.src = vid + '005612.mp4';
v.load();
break;
case 'Messages':
toggleAttr('#msg', 'hidden');
break;
case 'Controls':
toggleAttr('#vX', 'controls');
break;
default:
loadVideo();
break;
}
stamp(msg);
}
function loadVideo() {
var hrs = stamp();
// 05:00 - 09:59
if (hrs >= 5 && hrs < 10) {
v.src = vid + '005609.mp4';
v.load();
}
// 10:00 - 21:59
else if (hrs >= 10 && hrs < 22) {
v.src = vid + '005610.mp4';
v.load();
}
// 22:00 - 04:59
else {
v.src = vid + '005612.mp4';
v.load();
}
stamp('Autoload');
}
async function playMedia() {
try {
await v.play();
} catch (err) {
stamp('Promise Rejected');
}
}
function toggleAttr(selector, attr) {
var node = document.querySelector(selector);
var prop = node.getAttribute(attr);
if (!prop) {
node.setAttribute(attr, true);
} else {
node.removeAttribute(attr);
}
}
function stamp(str) {
var now = new Date();
var hrs = now.getHours();
var min = now.getMinutes();
var sec = now.getSeconds();
var h = hrs > 9 ? "" + hrs : "0" + hrs;
var m = min > 9 ? "" + min : "0" + min;
var s = sec > 9 ? "" + sec : "0" + sec;
var time = h + ":" + m + ":" + s;
r.textContent = str;
t.textContent = time;
return hrs;
}
</script>
</body>
There is no need to use setInterval; you only need to use an if statement or a switch case.
I removed the setInterval code and made one if statement. In the last condition, you need to change the double ampersand (&&/AND) to || (OR) - the (>22 OR <5)- otherwise it doesn't make sense. I tested the following by adjusting my system clock, it seems to work.
Here's a fiddle
Happy holidays!
var welcomeMovie1 = "http://mirrors.standaloneinstaller.com/video-sample/jellyfish-25-mbps-hd-hevc.mp4";
var welcomeMovie2 = "http://mirrors.standaloneinstaller.com/video-sample/TRA3106.mp4"
var welcomeMovie3 = "http://mirrors.standaloneinstaller.com/video-sample/Panasonic_HDC_TM_700_P_50i.mp4";
var messageTime = new Date().getHours();
var welcomeMsg = "";
var vid = " ";
//console.log(messageTime);
if (messageTime >= 5 && messageTime <= 10) {
welcomeMsg = "early bird";
vid = welcomeMovie1;
//console.log(welcomeMessage2);
}
else
if (messageTime >= 10 && messageTime < 22) {
welcomeMsg = "middle of day";
vid = welcomeMovie2;
//console.log(welcomeMessage2());
}
else
if (messageTime >= 22 || messageTime < 5) {
welcomeMsg = "night owl";
vid = welcomeMovie3;
}
////}, 1000 * 60);
playVideo(vid);
console.log("Hello! Your welcome message is " + welcomeMsg + " " + vid)
// promise functionb to create custom video controls and play functions
function playVideo(src) {
console.log("Hello! Your welcome message is " + welcomeMsg + " " + vid)
$("#playervideo").attr("src", src);
$("#playervideo")[0].muted = false;
if (autoplay == true) {
var playPromise = $("#playervideo")[0].play();
if (playPromise !== undefined) {
playPromise.then(function() {}).catch(function() {
if (autoplay == true) {
$("#video-unmute-button").addClass("show");
$("#playervideo")[0].muted = true;
var playPromise2 = $("#playervideo")[0].play();
playPromise2.then(function() {
}).catch(function() {
$("#video-start-button").addClass("show");
$("#video-start-button").on("click", function() {
$("#playervideo")[0].muted = false;
$("#playervideo")[0].play();
$("#video-start-button").removeClass("show");
});
});
console.log("pause force");
} else {
}
});
} else {}
} else {
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<iframe id="playervideo" controls src=" ">
</iframe>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am new to JavaScript and have been tasked with creating a simplified version of BlackJack. I've created 4 variables: var card1 = 0; same for card2, card3, and card4. To my understanding that would create a numeric variable. Then when I try to get a random number assigned to them, it's returning NaN.
var card1 = 0;
var card2 = 0;
var card3 = 0;
var card4 = 0;
card1 = Math.floor(Math.random() * 11 + 2);
card2 = Math.floor(Math.random() * 11 + 2);
card3 = Math.floor(Math.random() * 11 + 2);
card4 = Math.floor(Math.random() * 11 + 2);
console.log(card1, card2, card3, card4);
I've tried adding parseInt before the random with the same result. Any suggestions?
There's nothing wrong with the code you posted, at least in regards to NaN (Not a Number) values. Anyways, here is a nice fully-working HTML, CSS, JS Blackjack game. Maybe it can help you to find where you made mistakes, or at least inspire you go around this 'problem' in a slightly different manner.
<script>
window.addEventListener("load", start, false);
function start()
{
play();
}
function play()
{
var deck1 = new Deck();
deck1.createDeck();
deck1.shuffle();
deck1.deal21();
document.getElementById("hit").addEventListener("click", function(){deck1.hit();},false);
document.getElementById("stand").addEventListener("click", function(){deck1.stand();},false);
document.getElementById("replay").addEventListener("click", function(){deck1.deal21();}, false);
}
function Deck()
{
this.deck = new Array();
this.userTotal;
this.dealerTotal;
this.money = 100;
this.userBust;
this.dealerBust;
this.curusrHand;
this.curdlrHand;
var userHand = document.getElementById("user-hand");
var dealerHand = document.getElementById("dealer-hand");
var userScore = document.getElementById("user-score");
var dealerScore = document.getElementById("dealer-score");
var status = document.getElementById("game-status");
var moneyDiv = document.getElementById("money");
this.newDeck = function newDeck()
{
this.createDeck();
this.shuffle();
status.innerHTML="NEW DECK IN PLAY!";
}
this.createDeck = function createDeck()
{
var numCards=0;
var suit, symbol, name;
for(var k=1; k<=4; k++)
{
switch(k)
{
case 1: suit ="hearts";
break;
case 2: suit ="diamonds";
break;
case 3: suit ="spades";
break;
case 4: suit ="clubs";
break;
}
for(var i=1; i<=13; i++)
{
symbol = i;
switch(i)
{
case 1: name= "Ace";
symbol = "A";
break;
case 2: name= "two";
break;
case 3: name= "three";
break;
case 4: name= "four";
break;
case 5: name= "five";
break;
case 6: name= "six";
break;
case 7: name= "seven";
break;
case 8: name= "eight";
break;
case 9: name= "nine";
break;
case 10: name= "ten";
break;
case 11: name= "jack";
symbol = "J";
break;
case 12: name= "queen";
symbol = "Q";
break;
case 13: name= "king";
symbol = "K";
break;
}
this.deck[numCards] = new Card(suit, i, name, symbol);
numCards++;
}
}
}
this.shuffle = function shuffle()
{
var randomDeck = new Array();
var empty = false;
while(!empty)
{
var randomIndex = Math.floor(Math.random()*this.deck.length);
randomDeck.push(this.deck[randomIndex]);
this.deck.splice(randomIndex, 1);
if(this.deck.length <=0) empty = true;
}
for(var i=0; i<randomDeck.length; i++)
{
this.deck[i] = randomDeck[i];
}
};
this.calcValue = function calcValue(hand)
{
var val = 0;
var tempArr = hand;
tempArr.sort(function(a,b) { return parseFloat(a.val) - parseFloat(b.val) } );
for(var i=tempArr.length-1; i>=0; i--)
{
var temp = tempArr[i];
if(temp.val === 1 && val <=10)temp.val = 11;
else if(temp.val >=10) temp.val = 10;
val += temp.val;
}
return val;
};
this.emptyDeck = function emptyDeck()
{
if(this.deck.length < 1) return true;
else return false;
}
this.deal21 = function deal21()
{
status.innerHTML="";
this.money--;
//reset all the stuff that needs to be reset if the game is being replayed
money.innerHTML= "Money: " + this.money;
dealerHand.innerHTML="<h2>Dealer Hand</h2>";
userHand.innerHTML="<h2>User Hand</h2>";
this.userTotal=0;
this.dealerTotal=0;
this.userBust=false;
this.dealerBust=false;
hit.setAttribute("style", "");
stand.setAttribute("style", "");
dealerScore.setAttribute("style", "");
this.curusrHand = new Array();
this.curdlrHand = new Array();
for(i=0; i<2; i++)
{
if(this.emptyDeck())this.newDeck();
this.curusrHand.push(this.deck.pop());
userHand.innerHTML+=this.curusrHand[i].showCard();
}
this.userTotal = this.calcValue(this.curusrHand);
userScore.innerHTML=this.userTotal;
for(i=0; i<2; i++)
{
if(this.emptyDeck())this.newDeck();
this.curdlrHand.push(this.deck.pop());
dealerHand.innerHTML+=this.curdlrHand[i].showCard();
}
this.dealerTotal = this.calcValue(this.curdlrHand);
dealerScore.innerHTML=this.dealerTotal;
//hide dealers first card
var firstCard = dealerHand.getElementsByClassName("card")[0];
firstCard.setAttribute("id", "hidden-card");
var blackjack =true;
if(this.userTotal === 21 && this.dealerTotal < 21) this.gameOver(blackjack);
else if(this.dealerTotal === 21) this.gameOver();
};
this.hit = function hit()
{
if(this.emptyDeck())this.newDeck();
this.curusrHand.push(this.deck.pop());
userHand.innerHTML+=this.curusrHand[this.curusrHand.length-1].showCard();
this.userTotal = this.calcValue(this.curusrHand);
userScore.innerHTML=this.userTotal;
if(this.userTotal >21)
{
userScore.innerHTML+=" <span style='color:red; font-weight: bold;'> BUST</span>";
this.userBust = true;
this.gameOver();
}
};
this.stand = function stand()
{
while(this.dealerTotal < 17)
{
if(this.emptyDeck())this.newDeck();
this.curdlrHand.push(this.deck.pop());
dealerHand.innerHTML+=this.curdlrHand[this.curdlrHand.length-1].showCard();
this.dealerTotal = this.calcValue(this.curdlrHand);
dealerScore.innerHTML=this.dealerTotal;
if(this.dealerTotal > 21)
{
dealerScore.innerHTML+=" <span style='color:red; font-weight: bold;'> BUST</span>";
this.dealerBust = true;
}
}
this.gameOver();
}
this.gameOver = function gameOver(blackjack)
{
document.getElementById("hidden-card").setAttribute("id","");
dealerScore.setAttribute("style", "visibility: visible;");
hit.setAttribute("style", "visibility:hidden;");
stand.setAttribute("style", "visibility:hidden;");
if(blackjack)
{
this.money +=3;
status.innerHTML ="BLACKJACK!!!!!!!!!";
}
else if(this.userTotal > this.dealerTotal && this.userBust === false || this.dealerBust ===true)
{
//user wins
this.money+=2;
status.innerHTML ="YOU WIN!";
}
else if(this.userTotal === this.dealerTotal && this.userBust === false)
{
//push
this.money++;
status.innerHTML="PUSH :o";
}
else status.innerHTML="YOU LOSE!";
money.innerHTML="Money: "+this.money;
}
this.dump = function dump()
{
for(var i=0; i<this.deck.length; i++)
{
this.deck[i].showCard();
}
};
}
function Card(suit, val, name, symbol)
{
this.suit = suit;
this.val = val;
this.name = name;
this.symbol = symbol;
this.showCard =function showCard()
{
var html="";
switch(this.suit)
{
case "hearts": suit_text = "♥";
break;
case "diamonds": suit_text = "♦";
break;
case "spades": suit_text = "♠";
break;
case "clubs": suit_text = "♣";
break;
}
html="<div class='card " + this.suit + "'><div class='card-value'>" + this.symbol + "</div><div class='suit'>" + suit_text + "</div><div class='main-number'>"+this.symbol +"</div><div class='invert card-value'>"+this.symbol+"</div><div class='invert suit'>"+suit_text+"</div></div>";
return html;
}
}
</script>
div.card
{
display: inline-block;
width: 100px;
height: 150px;
border: solid 1px #333;
border-radius: 5px 5px 5px 5px;
float: left;
margin-right: 10px;
position: relative;
}
div.card.hearts, div.card.diamonds
{
color: red;
}
div.card div.main-number
{
font-size: 36px;
font-weight: bold;
text-align: center;
margin: 0px auto;
margin-top: 50px;
}
div.card-value, div.suit
{
position: absolute;
left: 5px;
}
div.card-value{top: 5px;}
div.card-value{top: 20px;}
div.card-value.invert, div.suit.invert
{
transform: rotate(180deg);
right: 5px;
text-align: right;
top: auto;
left: auto;
}
div.card-value.invert{bottom: 5px;}
div.suit.invert{bottom: 20px;}
div.dealer-area{}
div.user-area{float: left;}
div#user-score, div#dealer-score
{
display: inline-block;
}
div.score-parent
{
width: 100%;
display: inline-block;
}
div.score-parent p
{
display: inline-block;
}
div#dealer-score
{
visibility: hidden;
}
div.card#hidden-card
{
background-color: #CBE0FD;
}
div.card#hidden-card div
{
visibility: hidden;
}
div.controls input
{
margin-left: 20px;
width: 200px;
}
.score-parent {
color: blue;
font-weight: bold;
}
#user-hand {
font-family: cursive;
color: green;
font-weight: bold;
}
#dealer-hand {
font-family: cursive;
color: orange;
font-weight: bold;
}
input {
display: inline-block;
color: green;
font-weight: bold;
}
#money {
padding-bottom: 1rem;
color: gold;
letter-spacing: 3px;
font-weight: bold;
font-family: Arial;
}
<html>
<head>
</head>
<body>
<div id="game-status"></div>
<div class="user-area">
<div id="money"></div>
<div id="user-buttons" class="controls">
<input type="button" id="hit" value="Hit">
<input type="button" id="stand" value="Stand">
<input type="button" id="replay" value="Play Again">
</div>
<div class="score-parent">
<p>Score</p>
<div id="user-score"class="score">
</div>
</div>
<div id="user-hand" class="hand">
<h2>User Hand</h2>
</div>
</div>
<div class="dealer-area">
<div class="score-parent">
<p>Current Score: </p>
<div id="dealer-score"class="score">
</div>
</div>
<div id="dealer-hand" class="hand">
<h2>Dealer Hand</h2>
</div>
</div>
</body>
</html
In my AngularJS application I am attempting to add a Facebook Native Web Ad to one of my views. I followed the steps outlined in the documentation to generate the necessary HTML snippet and added this to my view.
My application is using ui-router to resolve routes. When visiting the route/view containing this code snippet the FB ad is not displayed and neither of the callbacks are invoked (onAdLoaded or onAdError).
Facebook Generated HTML Snippet (added to view):
<div style="display:none; position: relative;">
<iframe style="display:none;"></iframe>
<script type="text/javascript">
var data = {
placementid: 'xxxxxxxxxxx_xxxxxxxx',
format: 'native',
testmode: true,
onAdLoaded: function (element) {
console.log('Audience Network ad loaded');
element.style.display = 'block';
},
onAdError: function (errorCode, errorMessage) {
console.log('Audience Network error (' + errorCode + ') ' + errorMessage);
}
};
(function (w, l, d, t) {
var a = t();
var b = d.currentScript || (function () {
var c = d.getElementsByTagName('script');
return c[c.length - 1];
})();
var e = b.parentElement;
e.dataset.placementid = data.placementid;
var f = function (v) {
try {
return v.document.referrer;
} catch (e) {
}
return '';
};
var g = function (h) {
var i = h.indexOf('/', h.indexOf('://') + 3);
if (i === -1) {
return h;
}
return h.substring(0, i);
};
var j = [l.href];
var k = false;
var m = false;
if (w !== w.parent) {
var n;
var o = w;
while (o !== n) {
var h;
try {
m = m || (o.$sf && o.$sf.ext);
h = o.location.href;
} catch (e) {
k = true;
}
j.push(h || f(n));
n = o;
o = o.parent;
}
}
var p = l.ancestorOrigins;
if (p) {
if (p.length > 0) {
data.domain = p[p.length - 1];
} else {
data.domain = g(j[j.length - 1]);
}
}
data.url = j[j.length - 1];
data.channel = g(j[0]);
data.width = screen.width;
data.height = screen.height;
data.pixelratio = w.devicePixelRatio;
data.placementindex = w.ADNW && w.ADNW.Ads ? w.ADNW.Ads.length : 0;
data.crossdomain = k;
data.safeframe = !!m;
var q = {};
q.iframe = e.firstElementChild;
var r = 'https://www.facebook.com/audiencenetwork/web/?sdk=5.3';
for (var s in data) {
q[s] = data[s];
if (typeof(data[s]) !== 'function') {
r += '&' + s + '=' + encodeURIComponent(data[s]);
}
}
q.iframe.src = r;
q.tagJsInitTime = a;
q.rootElement = e;
q.events = [];
w.addEventListener('message', function (u) {
if (u.source !== q.iframe.contentWindow) {
return;
}
u.data.receivedTimestamp = t();
if (this.sdkEventHandler) {
this.sdkEventHandler(u.data);
} else {
this.events.push(u.data);
}
}.bind(q), false);
q.tagJsIframeAppendedTime = t();
w.ADNW = w.ADNW || {};
w.ADNW.Ads = w.ADNW.Ads || [];
w.ADNW.Ads.push(q);
w.ADNW.init && w.ADNW.init(q);
})(window, location, document, Date.now || function () {
return +new Date;
});
</script>
<script type="text/javascript" src="https://connect.facebook.net/en_US/fbadnw.js" async></script>
<style>
.thirdPartyRoot {
background-color: white;
color: #444;
border: 1px solid #ccc;
border-left: 0;
border-right: 0;
font-family: sans-serif;
font-size: 14px;
line-height: 16px;
width: 320px;
text-align: left;
position: relative;
}
.thirdPartyMediaClass {
width: 320px;
height: 168px;
margin: 12px 0;
}
.thirdPartySubtitleClass {
font-size: 18px;
-webkit-line-clamp: 1;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
height: 16px;
-webkit-box-orient: vertical;
}
.thirdPartyTitleClass {
padding-right: 12px;
line-height: 18px;
-webkit-line-clamp: 2;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
height: 36px;
-webkit-box-orient: vertical;
}
.thirdPartyCallToActionClass {
background-color: #416BC4;
color: white;
border-radius: 4px;
padding: 6px 20px;
float: right;
text-align: center;
text-transform: uppercase;
font-size: 11px;
}
.fbDefaultNativeAdWrapper {
font-size: 12px;
line-height: 14px;
margin: 12px 0;
height: 36px;
vertical-align: top;
}
</style>
<div class="thirdPartyRoot">
<a class="fbAdLink">
<div class="fbAdMedia thirdPartyMediaClass"></div>
<div class="fbAdSubtitle thirdPartySubtitleClass"></div>
<div class="fbDefaultNativeAdWrapper">
<div class="fbAdCallToAction thirdPartyCallToActionClass"></div>
<div class="fbAdTitle thirdPartyTitleClass"></div>
</div>
</a>
</div>
</div>
I noticed that the Facebook Audience Network JS is loaded asynchronously and suspected that I might have a race condition causing the issue.
<script type="text/javascript" src="https://connect.facebook.net/en_US/fbadnw.js" async></script>
To test this, I've moved the FB code snippet out of my view and into my SPA index.html. The ad appears as expected. What callback does the fbadnw.js script call once the script is loaded? Is the closure within the FB generated code being invoked before fbadnw.js is loaded perhaps?
index.html (works)
<!DOCTYPE html>
<html ng-app="kcl-app">
<head>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title ng-bind="pageTitle"></title>
</head>
<body>
<!-- ui-router view -->
<div ui-view></div>
<!-- FB Begin -->
<div class="fb-native">
<div style="display:none; position: relative;">
<iframe style="display:none;"></iframe>
<script type="text/javascript">
var data = {
placementid: 'xxxxxxxxxxx_xxxxxxxx',
format: 'native',
testmode: true,
onAdLoaded: function (element) {
console.log('Audience Network ad loaded');
element.style.display = 'block';
},
onAdError: function (errorCode, errorMessage) {
console.log('Audience Network error (' + errorCode + ') ' + errorMessage);
}
};
(function (w, l, d, t) {
var a = t();
var b = d.currentScript || (function () {
var c = d.getElementsByTagName('script');
return c[c.length - 1];
})();
var e = b.parentElement;
e.dataset.placementid = data.placementid;
var f = function (v) {
try {
return v.document.referrer;
} catch (e) {
}
return '';
};
var g = function (h) {
var i = h.indexOf('/', h.indexOf('://') + 3);
if (i === -1) {
return h;
}
return h.substring(0, i);
};
var j = [l.href];
var k = false;
var m = false;
if (w !== w.parent) {
var n;
var o = w;
while (o !== n) {
var h;
try {
m = m || (o.$sf && o.$sf.ext);
h = o.location.href;
} catch (e) {
k = true;
}
j.push(h || f(n));
n = o;
o = o.parent;
}
}
var p = l.ancestorOrigins;
if (p) {
if (p.length > 0) {
data.domain = p[p.length - 1];
} else {
data.domain = g(j[j.length - 1]);
}
}
data.url = j[j.length - 1];
data.channel = g(j[0]);
data.width = screen.width;
data.height = screen.height;
data.pixelratio = w.devicePixelRatio;
data.placementindex = w.ADNW && w.ADNW.Ads ? w.ADNW.Ads.length : 0;
data.crossdomain = k;
data.safeframe = !!m;
var q = {};
q.iframe = e.firstElementChild;
var r = 'https://www.facebook.com/audiencenetwork/web/?sdk=5.3';
for (var s in data) {
q[s] = data[s];
if (typeof(data[s]) !== 'function') {
r += '&' + s + '=' + encodeURIComponent(data[s]);
}
}
q.iframe.src = r;
q.tagJsInitTime = a;
q.rootElement = e;
q.events = [];
w.addEventListener('message', function (u) {
if (u.source !== q.iframe.contentWindow) {
return;
}
u.data.receivedTimestamp = t();
if (this.sdkEventHandler) {
this.sdkEventHandler(u.data);
} else {
this.events.push(u.data);
}
}.bind(q), false);
q.tagJsIframeAppendedTime = t();
w.ADNW = w.ADNW || {};
w.ADNW.Ads = w.ADNW.Ads || [];
w.ADNW.Ads.push(q);
w.ADNW.init && w.ADNW.init(q);
})(window, location, document, Date.now || function () {
return +new Date;
});
</script>
<script type="text/javascript" src="https://connect.facebook.net/en_US/fbadnw.js" async></script>
<style>
.thirdPartyRoot {
background-color: white;
color: #444;
border: 1px solid #ccc;
border-left: 0;
border-right: 0;
font-family: sans-serif;
font-size: 14px;
line-height: 16px;
width: 320px;
text-align: left;
position: relative;
}
.thirdPartyMediaClass {
width: 320px;
height: 168px;
margin: 12px 0;
}
.thirdPartySubtitleClass {
font-size: 18px;
-webkit-line-clamp: 1;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
height: 16px;
-webkit-box-orient: vertical;
}
.thirdPartyTitleClass {
padding-right: 12px;
line-height: 18px;
-webkit-line-clamp: 2;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
height: 36px;
-webkit-box-orient: vertical;
}
.thirdPartyCallToActionClass {
background-color: #416BC4;
color: white;
border-radius: 4px;
padding: 6px 20px;
float: right;
text-align: center;
text-transform: uppercase;
font-size: 11px;
}
.fbDefaultNativeAdWrapper {
font-size: 12px;
line-height: 14px;
margin: 12px 0;
height: 36px;
vertical-align: top;
}
</style>
<div class="thirdPartyRoot">
<a class="fbAdLink">
<div class="fbAdMedia thirdPartyMediaClass"></div>
<div class="fbAdSubtitle thirdPartySubtitleClass"></div>
<div class="fbDefaultNativeAdWrapper">
<div class="fbAdCallToAction thirdPartyCallToActionClass"></div>
<div class="fbAdTitle thirdPartyTitleClass"></div>
</div>
</a>
</div>
</div>
</div>
<!-- FB End -->
</body>
</html>
I was able to resolve this issue by editing the boilerplate code provided by FB. In a nutshell, the provided closure (minified) attempts to:
Locate the iframe element where the Ad will be rendered and set it's
src and other attributes.
Attach an event handler to listen for post messages "message".
Initialize the Ad with FB Audience Network (ADNW.init())
My problem was with the assumptions this code makes in Step 1.
var b = d.currentScript || (function() {
var c = d.getElementsByTagName('script');
return c[c.length - 1];
})();
var e = b.parentElement;
The above code is attempting to locate this DIV.
<div style="display:none; position: relative;">
It does this by first trying to locate the parent of the last script element on the page. This is brittle and, in my case, did not work. The last script element added in my document was not the one this code expected.
I modified this code to explicitly select the correct element by ID.
Added an ID to containing DIV:
<div id="fb-ad-container" style="display:none; position: relative;">
Simplify the DOM parsing code (step 1) to select this DIV by ID:
var e = d.getElementById("fb-ad-container");
By selecting the correct element by ID I was able to alleviate the need to locate the current script element. The rest of the script ran as expected.
I'd like to change css property depend on if-condition, what mean if the user press right key change background with specific color and if he press again change background color to other color.
$(document).ready(function() {
$(document).keyup(function(e) {
var counter = 0;
switch (e.which) {
case 39: // right
if (counter == 1) {
$(".my-div").css("background-color", "red");
counter = counter + 1;
}
if (counter == 2) {
$(".my-div").css("background-color", "yellow");
counter = counter + 1;
}
if (counter == 3) {
$(".my-div").css("background-color", "green")
counter = counter + 1;
}
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
console.log(counter);
})
.my-div {
width: 1170px;
height: 500px;
margin: 50px auto;
background-color: #0026ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-div"></div>
Use the stylesheet for background color changes. Here's how you can use the element to keep track of its current state while controlling styling at the same time:
$(document).ready(function() {
$(document).keyup(function(e) {
var counter = $(".my-div").attr('rcount') || 0;
//Resets to state0. Uncomment to stop after third trigger:
//if (counter < 3)
counter = (++counter % 4);
switch (e.which) {
case 39: // right
$(".my-div").attr("rcount", counter);
break;
default:
return;
}
e.preventDefault();
});
})
.my-div {
width: 200px;
height: 500px;
margin: 50px auto;
background-color: #0026ff;
}
.my-div[rcount='0'] { background-color: #0026ff;}
.my-div[rcount='1'] { background-color: red;}
.my-div[rcount='2'] { background-color: yellow; }
.my-div[rcount='3'] { background-color: green; }
/* Debug styles added to show current rcount value */
.my-div.debug { position:relative; }
.my-div.debug:before {
content: 'rcount ' attr( rcount );
color:white;
text-shadow:1px 1px 1px black;
position:absolute;
left:0;
top:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-div debug"></div>
Move counter out of keyup event and set it to 1, use triple equals === instead and add else to conditions so it will check the condition then move to the next one, inside those conditions increment the counter :
$(document).ready(function() {
var counter = 1;
$(document).keyup(function(e) {
switch (e.which) {
case 39: // right
if (counter === 1) {
$(".my-div").css("background-color", "red");
counter++;
}else if (counter === 2) {
$(".my-div").css("background-color", "yellow");
counter++;
}else if (counter === 3) {
$(".my-div").css("background-color", "green")
counter=1;
}
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
})
.my-div {
width: 117px;
height: 50px;
margin: 50px auto;
background-color: #0026ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-div"></div>
try this out , this will show random color when you click right arrow or left arrow
<html>
<head></head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style type="text/css">
.changeme{
width: 300px;
height: 300px;
background-color: orange;
}
</style>
<body>
<div class="changeme"></div>
</body>
<script type="text/javascript">
$("body").keydown(function(e){
if(e.keyCode == 37)//when you click the left arrow button
{
var theColor = getRandomColor();
$(".changeme").css({"background-color":theColor});
}
else if(e.keyCode == 39)//when you click right arrow button
{
var theColor = getRandomColor();
$(".changeme").css({"background-color":theColor});
}
});
//generate a random color
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</html>
I think this is working but not really. I also don't think that it is the best approach.
The timer serves as another function running while having the ability to change the pulsing rate of the image.
I have tried to use gifs instead of because they have different speeds, there isn't a smooth transition when switching between images.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.js"></script>
<style>
#red-square {
position: absolute;
display: inline-block;
z-index: 1;
top : 200px;
right: 200px;
height: 100px;
width: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id="result"></div>
<div id="red-square"></div>
<button onclick="speedOne();">speed one</button>
<button onclick="speedTwo();">speed two</button>
<button onclick="speedThree();">speed three</button>
<script>
var counter = 0,
stopTimeoutTwo = null,
stopTimeoutThree = null,
currentSpeed = "speed one";
function runCounter() {
counter++;
result.textContent = counter;
if(currentSpeed == "speed one") {
if((counter%60) == 0) {
$("#red-square").hide();
}else if((counter%60) != 0) {
$("#red-square").show();
}
}
else if(currentSpeed = "speed two") {
if((counter%45) == 0) {
$("#red-square").hide();
}else if((counter % 45) != 0) {
$("#red-square").show();
}
}else if(currentSpeed = "speed three") {
if((counter%30) == 0) {
$("#red-square").hide();
}else if((counter%30) != 0) {
$("#red-square").show();
}
}
if(counter < 1e5) timer = setTimeout(runCounter, 0);
}
runCounter();
function stepOne() {
currentSpeed = "speed one";
}
function stepTwo() {
currentSpeed = "speed two";
}
function stepThree() {
currentSpeed = "speed three";
}
</script>
</body>
</html>
You can use setInterval to create your efect like so: Fiddle!
This is the JS I used:
var speed = 4000;
var inter;
var square = document.getElementById("red-square");
square.style.backgroundColor = "red";
function myTime(){
inter = setInterval(function(){
console.log(square.style.backgroundColor+" "+speed);
if(square.style.backgroundColor == "red"){
square.style.backgroundColor = "blue";
}
else{
square.style.backgroundColor = "red";
}
}, speed);
}
function changSpeed(s){
clearInterval(inter);
speed = s;
inter=null;
myTime();
}
myTime();
the rest is your code.