Toggling between Boolean variable - javascript

I'm wondering how you would toggle between two boolean variables. This works correctly the first time running the code but then after running it a second time the output isn't correct.
Output first time running switchPlayer():
player1.isActive = false,
player2.isActive = true
Output second time running switchPlayer():
player1.isActive = true,
player2.isActive = true
Below is the code I wrote:
var Player = function(score, isActive){
this.score = score;
this.isActive = isActive;
}
Player.prototype.toggleIsActive = function(){
if(this.isActive === false){
this.isActive = true;
} else{
this.isActive = false;
}
}
function switchPlayer(){
if(player1.isActive === true){
player1.toggleIsActive();
player2.toggleIsActive();
} else{
player1.isActive = true;
}
}
var player1 = new Player("0", true);
var player2 = new Player("0", false);
switchPlayer();
switchPlayer();

You can simplify it like this:
Player.prototype.toggleIsActive = function(){
this.isActive = !this.isActive;
}
function switchPlayer(){
player1.toggleIsActive();
player2.toggleIsActive();
}
ToggleIsActive should just be the opposite of what it once was. Also note that switchPlayer only calls toggle with no specific logic.

You can achieve this by removing the if/else from the switchPlayer() implementation:
function switchPlayer(){
player1.toggleIsActive();
player2.toggleIsActive();
}
Also, consider simplifying your toggleIsActive() method on the Player prototype like so:
Player.prototype.toggleIsActive = function(){
this.isActive = !this.isActive;
}
Here's a full example:
var Player = function(score, isActive){
this.score = score;
this.isActive = isActive;
}
Player.prototype.toggleIsActive = function(){
this.isActive = !this.isActive;
}
function switchPlayer(){
player1.toggleIsActive();
player2.toggleIsActive();
}
var player1 = new Player("0", true);
var player2 = new Player("0", false);
console.log('player1.isActive', player1.isActive)
console.log('player2.isActive', player2.isActive)
console.log('----------------')
switchPlayer();
console.log('player1.isActive', player1.isActive)
console.log('player2.isActive', player2.isActive)
console.log('----------------')
switchPlayer();
console.log('player1.isActive', player1.isActive)
console.log('player2.isActive', player2.isActive)
console.log('----------------')

let player1 = {};
let player2 = {};
player1.isActive = false;
player2.isActive = true;
function toggle () {
player1.isActive = !player1.isActive;
player2.isActive = !player2.isActive;
console.log('player1', player1.isActive, 'player2', player2.isActive);
}
<button onclick="toggle()">Toggle</button>

Related

Self made text-to-speech in javascript doesn't work properly

We made a text-to-speech function in javascript. The only problem now is that it doesn't work properly. When the play button is pressed, it is supposed to tell everything that's within the body tags. The problem is that most of the times it's not working and when it does, it's telling also the javascript code which it's outside of the body tag. How can i fix this so that it's working everytime the play button is pressed and it's only telling everything in the body tag?
onload = function() {
if ('speechSynthesis' in window) with(speechSynthesis) {
var playEle = document.querySelector('#play');
var pauseEle = document.querySelector('#pause');
var stopEle = document.querySelector('#stop');
var flag = false;
playEle.addEventListener('click', onClickPlay);
pauseEle.addEventListener('click', onClickPause);
stopEle.addEventListener('click', onClickStop);
function onClickPlay() {
if (!flag) {
flag = true;
utterance = new SpeechSynthesisUtterance(document.querySelector('body').textContent);
utterance.lang = 'nl-NL';
utterance.rate = 0.7;
utterance.onend = function() {
flag = false;
playEle.className = pauseEle.className = '';
stopEle.className = 'stopped';
};
playEle.className = 'played';
stopEle.className = '';
speak(utterance);
}
if (paused) {
playEle.className = 'played';
pauseEle.className = '';
resume();
}
}
function onClickPause() {
if (speaking && !paused) {
pauseEle.className = 'paused';
playEle.className = '';
pause();
}
}
function onClickStop() {
if (speaking) {
stopEle.className = 'stopped';
playEle.className = pauseEle.className = '';
flag = false;
cancel();
}
}
}
else { /* speech synthesis not supported */
msg = document.createElement('h5');
msg.textContent = "Detected no support for Speech Synthesis";
msg.style.textAlign = 'center';
msg.style.backgroundColor = 'red';
msg.style.color = 'white';
msg.style.marginTop = msg.style.marginBottom = 0;
document.body.insertBefore(msg, document.querySelector('div'));
}
}
<button id=play>Play</button>
<button id=pause>Pause</button>
<button id=stop>Stop</button>
Define the DIV you want the Speech recognition to read from:
</head>
<body>
<div>
<button id=play>Play</button>
<button id=pause>Pause</button>
<button id=stop>Stop</button>
</div>
<div id="readFrom">
Just a test o my friend mplungjan
</div>
<script type="text/javascript">
window.onload = function () {
if ('speechSynthesis' in window)
with (speechSynthesis) {
var playEle = document.querySelector('#play');
var pauseEle = document.querySelector('#pause');
var stopEle = document.querySelector('#stop');
var flag = false;
playEle.addEventListener('click', onClickPlay);
pauseEle.addEventListener('click', onClickPause);
stopEle.addEventListener('click', onClickStop);
function onClickPlay() {
if (!flag) {
flag = true;
utterance = new SpeechSynthesisUtterance(document.querySelector('#readFrom').innerHTML);
utterance.lang = 'nl-NL';
utterance.rate = 0.7;
utterance.onend = function () {
flag = false;
playEle.className = pauseEle.className = '';
stopEle.className = 'stopped';
};
playEle.className = 'played';
stopEle.className = '';
speak(utterance);
}
if (paused) {
playEle.className = 'played';
pauseEle.className = '';
resume();
}
}
function onClickPause() {
if (speaking && !paused) {
pauseEle.className = 'paused';
playEle.className = '';
pause();
}
}
function onClickStop() {
if (speaking) {
stopEle.className = 'stopped';
playEle.className = pauseEle.className = '';
flag = false;
cancel();
}
}
}
else { /* speech synthesis not supported */
msg = document.createElement('h5');
msg.textContent = "Detected no support for Speech Synthesis";
msg.style.textAlign = 'center';
msg.style.backgroundColor = 'red';
msg.style.color = 'white';
msg.style.marginTop = msg.style.marginBottom = 0;
document.body.insertBefore(msg, document.querySelector('div'));
}
}
</script>
</body>
It should be very simple. I see on your line that you are querying all the body text Content but that should not be it. Go on your JS Console and query: document.querySelector('body').textContent
You should see exactly what you are passing as arguments to:
utterance = new SpeechSynthesisUtterance(document.querySelector('body').textContent);
So now it's up to you, you would have to filter what you want to be read by putting it in a specific DIV or stripping HTML from the page according to a complex logic keeping just what you want to read.

how can i migrate my js code to reactjs and call it?

hello everybody i'm a newbie so please forgive me for my silly questions i had
a js function in angular that let me scroll horizontally two divs simultaneously
ngOnInit() {
this.settActivityAndTaskCells();
//-------------------Begin Scroll-------------------
var isSyncingLeftScroll = false;
var isSyncingRightScroll = false;
var leftDiv = document.getElementById('top');
var rightDiv = document.getElementById('bot');
leftDiv.onscroll = function () {
if (!isSyncingLeftScroll) {
isSyncingRightScroll = true;
rightDiv.scrollLeft = this.scrollLeft;
}
isSyncingLeftScroll = false;
}
rightDiv.onscroll = function () {
if (!isSyncingRightScroll) {
isSyncingLeftScroll = true;
leftDiv.scrollLeft = this.scrollLeft;
}
isSyncingRightScroll = false;
}
//-------------------End Scroll-------------------
}
so i change it like this on reactjs
Scrolling = () => {
var isSyncingLeftScroll = false,
isSyncingRightScroll = false,
leftDiv = document.getElementById('top'),
rightDiv = document.getElementById('bot');
if (!isSyncingLeftScroll) {
isSyncingRightScroll = true;
rightDiv.scrollLeft = this.scrollLeft;
}
isSyncingLeftScroll = false;
if (!isSyncingRightScroll) {
isSyncingLeftScroll = true;
leftDiv.scrollLeft = this.scrollLeft;
}
isSyncingRightScroll = false;
}
and call it in the the div like
but the scroll doesn't work Thanks to anyone who takes time to help me, review and give feedback.
Your migration code is missing the most important part, binding the new functions to the scroll events. Should be:
Scrolling = () => {
var isSyncingLeftScroll = false,
isSyncingRightScroll = false,
leftDiv = document.getElementById('top'),
rightDiv = document.getElementById('bot');
leftDiv.onscroll = () => {
if (!isSyncingLeftScroll) {
isSyncingRightScroll = true;
rightDiv.scrollLeft = this.scrollLeft;
}
isSyncingLeftScroll = false;
};
rightDiv.onscroll = () => {
if (!isSyncingRightScroll) {
isSyncingLeftScroll = true;
leftDiv.scrollLeft = this.scrollLeft;
}
isSyncingRightScroll = false;
};
}

AnimateCC Canvas calling functions

I'm trying to change this code that I made from actionscript 3 to html5 canvas. I’m with doubt about calling functions that I created, for example:
function cleanSelection(){
this.a1.visible = true;
this.sa1.visible = false;
this.a2.visible = true;
this.sa2.visible = false;
}
function maxSelection(count){
cleanSelection();
count = 0;
return count;
}
I want to make this function below be able to call maxSelection() which calls cleanSelection()
this.a1.addEventListener("click", fl_Click.bind(this));
function fl_Click()
{
this.sa1.visible = true;
this.a1.visible = false;
count++;
if(count >= 2){
count = maxSelection(count);
}
}
How can I call these functions?
You Should put "bind(this)" in all methods:
function cleanSelection(){
this.a1.visible = true;
this.sa1.visible = false;
this.a2.visible = true;
this.sa2.visible = false;
}
function maxSelection(c){
cleanSelection.bind(this)();
c= 0;
return c;
}
var count = 0;
this.a1.addEventListener("click", fl_Click.bind(this));
function fl_Click() {
this.sa1.visible = true;
this.a1.visible = false;
count++;
if(count >= 2){
count = maxSelection.bind(this)(count);
}
}

Javascript callback managment

I'm having trouble with designing a class which exposes its actions through callbacks. Yes my approach works for me but also seems too complex.
To illustrate the problem I've drawn the following picture. I hope it is useful for you to understand the class/model.
In my approach, I use some arrays holding user defined callback functions.
....
rocket.prototype.on = function(eventName, userFunction) {
this.callbacks[eventName].push(userFunction);
}
rocket.prototype.beforeLunch = function(){
userFunctions = this.callbacks['beforeLunch']
for(var i in userFunctions)
userFunctions[i](); // calling the user function
}
rocket.prototype.lunch = function() {
this.beforeLunch();
...
}
....
var myRocket = new Rocket();
myRocket.on('beforeLunch', function() {
// do some work
console.log('the newspaper guys are taking pictures of the rocket');
});
myRocket.on('beforeLunch', function() {
// do some work
console.log('some engineers are making last checks ');
});
I'm wondering what the most used approach is. I guess I could use promises or other libraries to make this implementation more understandable. In this slide using callbacks is considered evil. http://www.slideshare.net/TrevorBurnham/sane-async-patterns
So, should I use a library such as promise or continue and enhance my approach?
var Rocket = function () {
this.timer = null;
this.velocity = 200;
this.heightMoon = 5000;
this.goingToMoon = true;
this.rocketStatus = {
velocity: null,
height: 0,
status: null
};
this.listener = {
};
}
Rocket.prototype.report = function () {
for (var i in this.rocketStatus) {
console.log(this.rocketStatus[i]);
};
};
Rocket.prototype.on = function (name,cb) {
if (this.listener[name]){
this.listener[name].push(cb);
}else{
this.listener[name] = new Array(cb);
}
};
Rocket.prototype.initListener = function (name) {
if (this.listener[name]) {
for (var i = 0; i < this.listener[name].length; i++) {
this.listener[name][i]();
}
return true;
}else{
return false;
};
}
Rocket.prototype.launch = function () {
this.initListener("beforeLaunch");
this.rocketStatus.status = "Launching";
this.move();
this.initListener("afterLaunch");
}
Rocket.prototype.move = function () {
var that = this;
that.initListener("beforeMove");
if (that.goingToMoon) {
that.rocketStatus.height += that.velocity;
}else{
that.rocketStatus.height -= that.velocity;
};
that.rocketStatus.velocity = that.velocity;
if (that.velocity != 0) {
that.rocketStatus.status = "moving";
}else{
that.rocketStatus.status = "not moving";
};
if (that.velocity >= 600){
that.crash();
return;
}
if (that.rocketStatus.height == 2000 && that.goingToMoon)
that.leaveModules();
if (that.rocketStatus.height == that.heightMoon)
that.landToMoon();
if (that.rocketStatus.height == 0 && !that.goingToMoon){
that.landToEarth();
return;
}
that.report();
that.initListener("afterMove");
that.timer = setTimeout(function () {
that.move();
},1000)
}
Rocket.prototype.stop = function () {
clearTimeout(this.timer);
this.initListener("beforeStop");
this.velocity = 0;
this.rocketStatus.status = "Stopped";
console.log(this.rocketStatus.status)
this.initListener("afterStop");
return true;
}
Rocket.prototype.crash = function () {
this.initListener("beforeCrash");
this.rocketStatus.status = "Crashed!";
this.report();
this.stop();
this.initListener("afterCrash");
}
Rocket.prototype.leaveModules = function () {
this.initListener("beforeModules");
this.rocketStatus.status = "Leaving Modules";
this.initListener("afterModules");
}
Rocket.prototype.landToMoon = function () {
this.initListener("beforeLandToMoon");
this.rocketStatus.status = "Landing to Moon";
this.goingToMoon = false;
this.initListener("afterLandToMoon");
}
Rocket.prototype.landToEarth = function () {
this.initListener("beforeLandToEarth");
this.stop();
this.rocketStatus.status = "Landing to Earth";
this.initListener("afterLandToEarth");
}
Rocket.prototype.relaunch = function () {
this.initListener("beforeRelaunch");
this.timer = null;
this.velocity = 200;
this.heightMoon = 5000;
this.goingToMoon = true;
this.rocketStatus = {
velocity: 200,
height: 0,
status: "relaunch"
};
this.launch();
this.initListener("afterRelaunch");
}
init;
var rocket = new Rocket();
rocket.on("afterLaunch", function () {console.log("launch1")})
rocket.on("afterLandToMoon", function () {console.log("land1")})
rocket.on("beforeLandToEarth", function () {console.log("land2")})
rocket.on("afterMove", function () {console.log("move1")})
rocket.on("beforeLaunch", function () {console.log("launch2")})
rocket.launch();
You can add any function before or after any event.
This is my solution for this kinda problem. I am not using any special methods anything. I was just wonder is there any good practise for this like problems. I dig some promise,deferred but i just can't able to to this. Any ideas ?

Javascript - Object not a collection

i try to create an video object with activex but i take this error : "Object not a collection". This is my code and error begins on line "this.parts = null;". There may be other things which causes error before this line. I search on the Net about this error but there is no example to solve it.
function detailKeyPress(evt) {
var evtobj=window.event? event : evt;
switch (evtobj.keyCode) {
case KEYS.OK:
if (player.isFullScreen == false)
player.makeFullScreen();
else
player.makeWindowed();
break;
case KEYS.PLAY:
player.isPlaying = true;
player.object.play(1);
break;
case KEYS.PAUSE:
player.pause();
break;
case KEYS.STOP:
player.makeWindowed();
player.stop();
break;
}
}
function Player(id) {
this.id = id;
this.object = document.getElementById(id);
this.isFullScreen = false;
this.isPlaying = false;
this.parts = null;
return this;
}
Player.prototype.play = function () {
this.isPlaying = true;
return this.object.play(1);
}
Player.prototype.playByUrl = function (url) {
this.object.data = url;
return this.play();
}
document.onkeydown = function (evt) {
detailKeyPress(evt);
}
window.onload = function () {
player = new Player('playerObject');
player.playByUrl($mp4Link);
}
Player.prototype.makeFullScreen = function () {
try {
this.object.setFullScreen(true);
this.isFullScreen = true;
}
catch (ex) {//If philips
this.object.fullScreen = true;
this.isFullScreen = true;
}
}
Player.prototype.makeWindowed = function () {
try {
this.object.setFullScreen(false);
this.isFullScreen = false;
}
catch (ex) { //If philips
this.object.fullScreen = false;
this.isFullScreen = false;
}
}
Player.prototype.pause = function () {
this.isPlaying = false;
this.object.play(0);
}
Player.prototype.stop = function () {
this.isPlaying = false;
this.object.stop();
}
This may caused by your registry. If you clean it, you can solve or probably a bug. I have searched also a lot about this error. There is no another thing to say.

Categories

Resources