Javascript, JQuery Previous button - javascript

I need some help with this code. I want to create an event click button for previous. How can I do this using a little code? some thing similar to my Next button click event.
Here is my full code.
$(document).ready(function() {
var nextSlide = $("#slides img:first-child");
var nextCaption;
var nextSlideSource;
var counter = 0;
// the function for running the slide show
var runSlideShow = function() {
$("#caption").fadeOut(1000);
$("#slide").fadeOut(1000,
function () {
if (nextSlide.next().length === 0) {
nextSlide = $("#slides img:first-child");
}
else {
nextSlide = nextSlide.next();
}
nextSlideSource = nextSlide.attr("src");
nextCaption = nextSlide.attr("alt");
$("#slide").attr("src", nextSlideSource).fadeIn(1000);
$("#caption").text(nextCaption).fadeIn(1000);
}
);
};
// start the slide show
var timer = setInterval(runSlideShow, 3000);
$("#play").on("click", function() {
if($(this).val() === "Pause") {
clearInterval(timer);
$(this).val("Play");
$("#prev").prop("disabled", false);
$("#next").prop("disabled", false);
}
else if ($(this).val() === "Play") {
timer = setInterval(runSlideShow, 3000);
$(this).val("Pause");
$("#prev").prop("disabled", true);
$("#next").prop("disabled", true);
}
});
var imag = $("#slides img").index();
var imageSize = $("#slides img").length - 1;
$("#next").on("click", function (e) {
e.preventDefault();
if (imag === imageSize) {
$("#next").prop("disabled", true);
}
else {
++imag;
runSlideShow(1);
}
});
});
body {
font-family: Arial, Helvetica, sans-serif;
width: 380px;
height: 350px;
margin: 0 auto;
padding: 20px;
border: 3px solid blue;
}
h1, h2, ul, p {
margin: 0;
padding: 0;
}
h1 {
padding-bottom: .25em;
color: blue;
}
h2 {
font-size: 120%;
padding: .5em 0;
}
img {
height: 250px;
}
#slides img {
display: none;
}
#buttons {
margin-top: .5em;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Slide Show</title>
<link rel="stylesheet" href="main.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="slide_show.js"></script>
</head>
<body>
<section>
<h1>Fishing Slide Show</h1>
<h2 id="caption">Casting on the Upper Kings</h2>
<img id="slide" src="images/casting1.jpg" alt="">
<div id="slides">
<img src="images/casting1.jpg" alt="Casting on the Upper Kings">
<img src="images/casting2.jpg" alt="Casting on the Lower Kings">
<img src="images/catchrelease.jpg" alt="Catch and Release on the Big Horn">
<img src="images/fish.jpg" alt="Catching on the South Fork">
<img src="images/lures.jpg" alt="The Lures for Catching">
</div>
<div id="buttons">
<input type="button" id="prev" value="Previous" disabled>
<input type="button" id="play" value="Pause">
<input type="button" id="next" value="Next" disabled>
</div>
</section>
</body>
</html>
I thought of during it this way, but that is not working.
$("#prev").on("click", function () {
if (imag === imageSize) {
$("#prev").prop("disabled", true);
}
else {
++imag;
runSlideShow(-1);
}
});
Something similar to this Next button click event.
$("#next").on("click", function (e) {
e.preventDefault();
if (imag === imageSize) {
$("#next").prop("disabled", true);
}
else {
++imag;
runSlideShow(1);
}
});
Any help please.

test my idea =)
var mySlide = function(){
var index = 0;
var timer = false;
var self = this;
self.data = [];
self.start = function(){
timer = setInterval(self.next, 3000);
return self;
};
self.stop = function(){
clearInterval(timer);
timer = false;
return self;
};
self.pause = function(){
if(timer == false){
self.start();
} else {
self.stop();
}
};
self.next = function(){
if(self.data.length > 0){
self.stop().start(); // reset the timer
index++;
self.update();
}
};
self.prev = function(){
if(self.data.length > 0 && index > 0){
self.stop().start(); // reset the timer
index--;
self.update();
}
};
self.update = function(){
var item = self.data[index % self.data.length]; // calculating the value of INDEX
$('.print').fadeOut(1000,function(){
$(this).html(item).fadeIn(1000);
});
};
}
// RUN CODE!
var test = new mySlide();
test.data = [ // LOAD ITEM!
'food',
'bar',
$('<img/>').attr('src','https://www.google.it/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png')
];
test.start().update(); // START!
$('.prev').click(test.prev); // add event!
$('.pause').click(test.pause);
$('.next').click(test.next);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="print"></div>
<input type="button" value="prev" class="prev">
<input type="button" value="pause" class="pause">
<input type="button" value="next" class="next">

Related

trying to show and edit some boxes with jquery

i am trying to create divs that are boxes and do the following on them
1) change the background color
2) make them look like a circle
3) create more boxes(divs)
each has a individual button to fire the events but the boxes wont show and the only the second button works,with the console.log and the console doesnt show any errors at all
here is the html code and style
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" >
</script>
<script src="Query_script.js"></script>
<div class= "packages">
<div></div>
<div></div>
</div>
<button id = "change">Turn Colors on/off</button><br>
<button id = "R-border">Rounded Corners on/off</button><br>
<button id = "create">Add an extra box </button> <br>
<style>
.packages{
border-color: black;
border-width: 5px;
height: 75 px;
width: 75 px;
}
</style>
</body>
</html>
and here is the js and query
let pack=document.getElementById("packages");
let rad= document.getElementById("R-border");
let Adder=document.getElementById("create");
let checker=true;
$(document).ready(function() {
$("#changer").click(function(){
console.log("clicked1");
if (checker==true){
$('.pack').css('background-color','red');
checker=false;
}
else{
$('.packa>div').css('background-color','white');
checker=true;
}
});
});
$(document).ready(function() {
$("#R-border").click(function(){
if(checker==true){
console.log("clicked2");
$('.pack').css("border-radius","50%");
checker=false;
}
else{
$('.pack').css("border-radius");
}
});
});
$(document).ready(function() {
$("#Adder").click(function(){
console.log("clicked3");
$('.pack').append("<div>");
});
});
Maintain CSS selector names properly
I have done some modifications to HTML and javascript. Try this... It's working properly.
let pack = document.getElementById("packages");
let rad = document.getElementById("R-border");
let Adder = document.getElementById("create");
let checker = true;
$(document).ready(function () {
$("#change").click(function () {
console.log("clicked1");
if (checker == true) {
$('.packages').css('background-color', 'red');
checker = false;
} else {
$('.packages > div').css('background-color', 'white');
checker = true;
}
});
});
$(document).ready(function () {
$("#R-border").click(function () {
console.log("clicked2");
if (checker == true) {
$('.packages').css("border-radius", "50%");
checker = false;
} else {
$('.packages').css("border-radius");
}
});
});
$(document).ready(function () {
$("#create").click(function () {
console.log("clicked3");
$('.packages').append("<div>");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="Query_script.js"></script>
<div class="packages">
<div></div>
<div></div>
</div>
<button id="change">Turn Colors on/off</button>
<br>
<button id="R-border">Rounded Corners on/off</button>
<br>
<button id="create">Add an extra box</button>
<br>
<style>
.packages {
border-color: black;
border-width: 5px;
height: 75px;
width: 75px;
}
</style>

Changing Iframes HTML

I need a script to change the iframes src every certain amount of seconds. The time between the change is different between each one.
Example:
Page Loads
Google.com is loaded.
15 seconds later
Yahoo.com is loaded.
37 seconds later
Ask.com is loaded.
12 seconds later
Dogpile.com is loaded.
and so on and so forth.
I've tried that:
<html>
<head>
<meta charset="utf-8" />
<title>Monitor PresidĂȘncia</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.js"></script>
</head>
<body>
<div style="width: 100%; display: flex;">
<div class="ui teal progress" data-percent="0" id="example1" style="width: 90%;margin-bottom: 0px">
<div class="bar"></div>
</div>
<div class="ui icon buttons" style="width: 10%">
<button class="ui button" style="width: 25%" onclick="menos_um()">
<i class="left chevron icon"></i>
</button>
<button class="ui button " style="width: 25%" onclick="inicia()">
<i class="play icon"></i>
</button>
<button class="ui button" style="width: 25%" onclick="para_aplicacao()">
<i class="pause icon"></i>
</button>
<button class="ui button" style="width: 25%" onclick="mais_um()">
<i class="right chevron icon"></i>
</button>
</div>
</div>
<iframe id="envase" class="frame_mon" style="width: 100%;height: 100%;" src="www.google.com.br"></iframe>
<iframe id="frete_hl" class="frame_mon" style="width: 100%;height: 100%;display: none;" src="www.yahoo.com.br"></iframe>
<iframe id="frete_hl_acum" class="frame_mon" style="width: 100%;height: 100%;display: none;" src="www.terra.com.br"></iframe>
</body>
<script>
var arr_monitores = ["envase", "frete_hl", "frete_hl_acum"];
var num_monitor = 0;
var progresso = 0;
var myVar;
var setintervalatualizaframe;
function mais_um() {
/* if (num_monitor === 2) {
num_monitor = 0;
} else {
num_monitor++;
}
$('.frame_mon').css('display', 'none');
document.getElementById(arr_monitores[num_monitor]).style.display = "";*/
progresso = 100;
myStopFunction();
inicia();
/* if (num_monitor === 2) {
num_monitor = 0;
} else {
num_monitor++;
}*/
};
function menos_um() {
//progresso = 100;
if (num_monitor === 0) {
num_monitor = 2;
} else {
num_monitor--;
}
$('.frame_mon').css('display', 'none');
document.getElementById(arr_monitores[num_monitor]).style.display = "";
progresso = 0;
myStopFunction();
inicia();
};
function inicia() {
clearInterval(setintervalatualizaframe);
myStopFunction();
myVar = setInterval(function () {
if (progresso === 100) {
progresso = 0;
if (num_monitor === 2) {
location.reload();
//num_monitor = 0;
} else {
num_monitor++;
}
$('.frame_mon').css('display', 'none')
document.getElementById(arr_monitores[num_monitor]).style.display = "";
};
progresso++;
progresso++;
$('#example1').data('percent', progresso);
$('#example1').progress();
}, 3800);
}
function myStopFunction() {
clearInterval(myVar);
//atualiza_frame();
}
inicia();
function para_aplicacao(){
clearInterval(myVar);
atualiza_frame();
}
function atualiza_frame() {
clearInterval(setintervalatualizaframe);
setintervalatualizaframe = setInterval(function () {
document.getElementById(arr_monitores[num_monitor]).src=document.getElementById(arr_monitores[num_monitor]).src;
},1);
}
</script>
</html>
The way you are using setInterval and setTimeout is not properly
handled, as it creates a timer id to schedule execution. 0
A much more efficient way is to use the Promises async library, which is displayed below. 1
For websites that won't work, they are using a response header that won't allow their pages to be framed. You can work around this with some back-end program, where the server loads the web files then forwards them. 2
<!DOCTYPE html>
<html>
<head>
<title> Hello </title>
<style>
iframe {
display: block;
width: 1000px;
height: 500px;
margin-left: auto;
margin-right: auto;
}
iframe:focus {
outline: none;
}
button {
display: block;
margin: auto auto;
}
label {
display: block;
margin-left: auto;
margin-right: auto;
}
input {
display: block;
margin: auto auto;
}
</style>
</head>
<body>
<div id='main'>
<button id='wait' onclick='wait()'>Wait</button>
<label>Seconds</label>
<input type='number' id='seconds' placeholder='milliseconds'>
<button id='switching' onclick='webSwitch()'>Switch sites</button>
<iframe id='switchMe' src='https://codepen.io'></iframe>
</div>
<script>
//Array of webpages
var webList = ["https://www.bing.com", "https://www.walmart.com","https://www.codepen.io"];
//For tracking position in array
var count = 0;
//Function to be ran by event
function webSwitch() {
console.log('I have been called');
if (count >= webList.length) {
count = 0;
}
//Setting new URL
document.getElementById('switchMe').src = webList[count];
//Make sure to use next URL
count++;
}
function wait() {
console.log('Click!');
var numMS = document.getElementById('seconds').value;
sleep(numMS).then(() => {
webSwitch();
})
}
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
</script>
</body>
</html>

move shape to different directions

Task:
I created a shape with 4 buttons, and need it to move to 4 directions depending on the button clicked (pure JS).
This is what I created - check out the snippet.
Problem:
Left/Right directions work great, but Up/Down do not.
Any idea why? Looks like both directions are identical. :/
Thanks a lot for your help, much appreciated!
var shape = document.getElementById("shape"),
leftBtn = document.getElementById("leftBtn"),
rightBtn = document.getElementById("rightBtn"),
upBtn = document.getElementById("upBtn"),
downBtn = document.getElementById("downBtn");
leftBtn.onclick = function(){
moveLeft();
}
rightBtn.onclick = function(){
moveRight();
}
upBtn.onclick = function(){
moveUp();
}
downBtn.onclick = function(){
moveDown();
}
function moveLeft() {
var val = (parseInt(shape.style.left) || 0) - 50;
shape.style.left = val + "px";
}
function moveUp() {
var val = (parseInt(shape.style.top) || 0) - 50;
shape.style.left = val + "px";
}
function moveRight() {
var val = (parseInt(shape.style.left) || 0) + 50;
shape.style.left = val + "px";
}
function moveDown() {
var val = (parseInt(shape.style.top) || 0) + 50;
shape.style.left = val + "px";
}
body{
background-color: black;
}
#shape{
background-color: red;
width: 100px;
height: 100px;
border-radius: 50%;
position: relative;
}
<html>
<head>
<title>JavaScript and the Document Object Model</title>
<link rel="stylesheet" type="text/css" href="shape.css">
</head>
<body>
<div id="container">
<div id="shape">
</div>
<div id="buttons">
<button class="button" id="leftBtn" direction="left">left</button>
<button class="button" id="upBtn" direction="up">up</button>
<button class="button" id="downBtn" direction="down">down</button>
<button class="button" id="rightBtn" direction="right">right</button>
</div>
</div>
<script type="text/javascript" src="shape.js"></script>
</body>
</html>
As pointed by #Temani, in functions moveUp and moveDown, changing shape.style.left to shape.style.top will solve the problem.
var shape = document.getElementById("shape"),
leftBtn = document.getElementById("leftBtn"),
rightBtn = document.getElementById("rightBtn"),
upBtn = document.getElementById("upBtn"),
downBtn = document.getElementById("downBtn");
leftBtn.onclick = function(){
moveLeft();
}
rightBtn.onclick = function(){
moveRight();
}
upBtn.onclick = function(){
moveUp();
}
downBtn.onclick = function(){
moveDown();
}
function moveLeft() {
var val = (parseInt(shape.style.left) || 0) - 50;
shape.style.left = val + "px";
}
function moveUp() {
var val = (parseInt(shape.style.top) || 0) - 50;
shape.style.top = val + "px";
}
function moveRight() {
var val = (parseInt(shape.style.left) || 0) + 50;
shape.style.left = val + "px";
}
function moveDown() {
var val = (parseInt(shape.style.top) || 0) + 50;
shape.style.top = val + "px";
}
body{
background-color: black;
}
#shape{
background-color: red;
width: 100px;
height: 100px;
border-radius: 50%;
position: relative;
}
<html>
<head>
<title>JavaScript and the Document Object Model</title>
<link rel="stylesheet" type="text/css" href="shape.css">
</head>
<body>
<div id="container">
<div id="shape">
</div>
<div id="buttons">
<button class="button" id="leftBtn" direction="left">left</button>
<button class="button" id="upBtn" direction="up">up</button>
<button class="button" id="downBtn" direction="down">down</button>
<button class="button" id="rightBtn" direction="right">right</button>
</div>
</div>
<script type="text/javascript" src="shape.js"></script>
</body>
</html>

Auto record and allow to play once using JQuery

Hiii Everyone,
Below is the sample code for record.
<html>
<body>
<audio controls autoplay></audio>
<input onclick="startRecording()" type="button" value="start recording" />
<input onclick="stopRecording()" type="button" value="stop recording and play" />
<script>
var onFail = function(e) {
console.log('Rejected!', e);
};
var onSuccess = function(s) {
stream = s;
}
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
var stream;
var audio = document.querySelector('audio');
function startRecording() {
if (navigator.getUserMedia) {
navigator.getUserMedia({audio: true}, onSuccess, onFail);
} else {
console.log('navigator.getUserMedia not present');
}
}
function stopRecording() {
audio.src = window.URL.createObjectURL(stream);
}
</script>
</body>
</html>
What I want to do is setInterval for 40 secs it will buffer for 40 secs like recording will start in 40secs timer will run after 40 secs it will show the play button to check audio recorded.Below I had added sample screenshots
Progress bar will show the recording..Similarly there will be some question with audio there I need to start recording once audio complete play.If anybody knows solution for this issue Please help me.Thanks for ur support
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<style>
.center_div {
width: 500px;
height: 100px;
background-color: #f5f5f5;
border: 1px solid #808080;
position: absolute;
top: 50%;
left: 50%;
margin-left: -250px;
/* half width*/
margin-top: -50px;
/* half height*/
padding: 25px;
}
.recording_label {
display: block;
text-align: center;
padding: 10px;
font-family: sans-serif;
font-size: 1.1em;
margin-bottom: 25px;
}
.loader_bg {
min-width: 100%;
background: #c5c5c5;
min-height: 20px;
display: block;
}
.loader_bg1 {
min-width: 90%;
background: grey;
min-height: 20px;
display: inline-block;
position: relative;
top: -20px;
}
</style>
</head>
<body>
<audio controls autoplay></audio>
<input onclick="startRecording();" type="button" value="start recording" />
<input onclick="stopRecording();" type="button" value="stop recording and play" />
<div class="center_div">
<span class="recording_label">Please wait...</span>
<span class="loader_bg"></span>
<span class="loader_bg1"></span>
</div>
<script>
var onFail = function(e) {
console.log('Rejected!', e);
};
var onSuccess = function(s) {
stream = s;
}
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
var stream;
var audio = document.querySelector('audio');
function startRecording() {
if (navigator.getUserMedia) {
navigator.getUserMedia({
audio: true
}, onSuccess, onFail);
} else {
console.log('navigator.getUserMedia not present');
}
}
function stopRecording() {
audio.src = window.URL.createObjectURL(stream);
}
$(function() {
var max = 40;
var count = max + 1;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
$(".recording_label").html("Recording...");
$('.loader_bg1').css({
'min-width': '' + (100) + '%'
})
startRecording();
recordingSec(40);
return;
}
$(".recording_label").html("Recording will begin in " + count + " sec.");
var percent = (count / max) * 100;
$('.loader_bg1').css({
'min-width': '' + (100 - percent) + '%'
})
}
});
function recordingSec(sec) {
var count = sec + 1;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
$(".recording_label").html("Recording stopped...Playing");
$('.loader_bg1').css({
'min-width': '' + (100) + '%'
})
stopRecording();
return;
}
$(".recording_label").html("Recording started [ " + (sec - count) + " / " + sec + " ] sec.");
var percent = (count / sec) * 100;
$('.loader_bg1').css({
'min-width': '' + (100 - percent) + '%'
})
}
}
</script>
</body>
</html>
Try To Use:
.btn-primary-success {
color: #fff;
background-color: #04b5e0;
border-color: #04b5e0;
}
.btn-primary-success:hover, .btn-primary-success:focus, .btn-primary-success:active, .btn-primary-success.active, .open .dropdown-toggle.btn-primary-success {
color: #fff;
background-color: #09a0c5;
border-color: #09a0c5;
}
Using Html Code:
<div style="text-align: left; padding: 10px;">
<label style="margin-right: 10px; font-size: 14px !important;">Dictate Status</label>
<a class="btn btn-primary-success pauseAudioDocWS pause" title="Pause" style="display: none; margin-right: 5px;"
data-value="">
<i class="imgpauseWS fa fa-lg fa-pause" style="cursor: pointer; margin: 2px 5px;"></i>
<b class="ppauseWS btn-primary-success">Pause</b></a>
<a class="btn btn-primary-success recordAudioDocWS inActiveWS" title="Start" style="margin-right: 20px;"
data-value="">
<b class="pplayWS">Click here to Start</b>
<i class="imgplayWS fa fa-lg fa-microphone" style="cursor: pointer; margin: 2px 5px;"></i>
</a>
<span class="stopwatchWS" style="display: none; margin-right: 10px;">00:00:00</span>
</div>
Download Audio and Timer File in github links:
https://github.com/fezalhalai/AudioRecorder.js
Using Jquery Code:
<script src="../js/StopTimer.js"></script>
<script src="../js/jquery.timer.js"></script>
<script src="../js/AudioRecorder.js"></script>
<script src="https://cdn.webrtc-experiment.com/RecordRTC.js" type="text/javascript"></script>
<script src="https://cdn.webrtc-experiment.com/gif-recorder.js" type="text/javascript"></script>
<script src="https://cdn.webrtc-experiment.com/gumadapter.js" type="text/javascript"></script>
<script src="https://cdn.webrtc-experiment.com/DetectRTC.js" type="text/javascript"> </script>
<script type="text/javascript">
$(document).ready(function () {
var oldRecorderWS;
$('.recordAudioDocWS').click(function () {
var $this = $(this);
if (oldRecorderWS != undefined) {
if (oldRecorderWS != document.tmId) {
alert('Dictating Already In Progress, Please Stop Previous Dictating To Continue');
return;
}
}
var checkin_id = document.tmId;
localStorage.setItem('checkin_id', checkin_id);
localStorage.setItem('Tran_Type', 'W');
oldRecorderWS = document.tmId;
var roomId = document.tmId;
localStorage.setItem('roomId', roomId);
var isRecording = false;
$(".isActiveWS").each(function () {
if ($(this).hasClass('isActiveWS')) {
isRecording = true;
}
});
if (isRecording == true) {
document.isRecordActivityPerforms = true;
if (confirm('Dictating in progress do you want to stop and save?')) {
oldRecorderWS = undefined;
$this.next('span').css('display', 'none');
Example1.resetStopwatch();
$('.stoprecmessage').css('display', 'block');
$(".isActiveWS").each(function () {
$(this).addClass('inActiveWS');
$(this).removeClass('isActiveWS');
$(this).find('.pplayWS').text('Click here to Start');
//$(this).find('.imgplay').attr('src', 'img/play.png');
$(this).find('.imgplayWS').addClass('fa-stop');
$(this).find('.imgplayWS').addClass('fa-microphone');
$(this).attr('title', 'Start');
});
//$('.tbothers').css('pointer-events', 'auto');
$('.btn-ws-next').removeAttr('disabled', '');
$('.btn-ws-prv').removeAttr('disabled', '');
$this.prev('a').css('display', 'none');
$this.prev('a').addClass('pause');
StartRecording();
document.isRecordActivityPerform = false;
//$this.next().next('img').removeClass('hidden');
if ($(CurruntAudioRecRow).parent().parent().find('.hdtmvid').val() == document.tmId) {
$(CurruntAudioRecRow).parent().parent().find('td .audioList').removeClass();
$(CurruntAudioRecRow).parent().parent().find('td .REC').removeClass('hidden');
$(CurruntAudioRecRow).parent().parent().find('td .PEN').addClass('hidden');
}
}
}
else {
$('.btn-ws-next').attr('disabled', 'disabled');
$('.btn-ws-prv').attr('disabled', 'disabled');
document.isRecordActivityPerform = true;
$this.next('span').css('display', 'inline');
$this.next().next('img').addClass('hidden');
Example1.init($this.next('span'));
Example1.resetStopwatch();
Example1.Timer.toggle();
$this.removeClass('inActiveWS');
$this.addClass('isActiveWS');
$this.find('.pplayWS').text('Stop');
//$this.find('.imgplay').attr('src', 'img/stop.png');
$this.find('.imgplayWS').removeClass('fa-microphone');
$this.find('.imgplayWS').addClass('fa-stop');
$this.attr('title', 'Stop');
$this.prev('a').css('display', 'inline-table');
StartRecording();
}
});
$('.pauseAudioDocWS').click(function () {
document.isRecordActivityPerform = true;
var $this = $(this);
Example1.Timer.toggle();
var btnStartRecording = document.querySelector('#btn-start-recording');
if ($(this).hasClass('pause')) {
btnStartRecording.recordRTC.pauseRecording();
recordingPlayer.pause();
$(this).addClass('resume');
$(this).removeClass('pause');
$(this).find('.ppauseWS').text('Resume');
//$(this).find('.imgpause').attr('src', 'img/play.png');
$(this).find('.imgpauseWS').removeClass('fa-pause');
$(this).find('.imgpauseWS').addClass('fa-microphone');
$(this).attr('title', 'Resume');
$(this).next('a').css('pointer-events', 'none');
$(this).next('a').attr('disabled', 'disabled');
}
else if ($(this).hasClass('resume')) {
btnStartRecording.recordRTC.resumeRecording();
recordingPlayer.play();
$(this).addClass('pause');
$(this).removeClass('resume');
$(this).find('.ppauseWS').text('Pause');
//$(this).find('.imgpause').attr('src', 'img/pause.png');
$(this).find('.imgpauseWS').removeClass('fa-microphone');
$(this).find('.imgpauseWS').addClass('fa-pause');
$(this).attr('title', 'Pause');
$(this).next('a').css('pointer-events', 'auto');
$(this).next('a').removeAttr('disabled');
}
});
});
</script>

Function keeps executing piece of code even if changed

I'm currently having a problem making a Tic-Tac-Toe game where even if i change the "state" variable it keeps executing the code inside it, how can i solve this problem? Is there a easy way to keep executing constant code for making a game?
$(document).ready(function() {
gameManager();
});
$(document).ready(function() {
gameManager();
});
var playerSelect, aiSelect = "";
var state = "choose";
var turn = "player";
var gameOn = true;
function gameManager() {
if (state == "choose") {
chooseSide();
} else if (state == "play") {
createGrid();
if (turn == "player") {
playerChoose();
console.log("Player's turn");
} else {
playerChoose();
console.log("Enemy's turn");
}
}
}
function playerChoose() {
$('.gridElement').click(function() {
$(this).html('<div class="gridElement">' + playerSelect + '</div>');
});
}
function chooseSide() {
console.log(state);
$('#textContainer').html('<p> Choose Side: </p> <div class="chooseButton">X</div> <div class="chooseButton">O</div>');
$('.chooseButton').click(function() {
console.log(state);
playerSelect = $(this).html();
if (playerSelect == "X") {
aiSelect = "O";
} else {
aiSelect = "X";
}
state = "play"
console.log(state);
});
}
function createGrid() {
for (var i = 0; i < 9; i++) {
$('#gridContainer').append('<div class="gridElement"> </div>');
}
var gridElementSize = $('#gridContainer').width() / 3;
$('.gridElement').css({
'width': gridElementSize,
"height": gridElementSize
});
}
#gridContainer {
border: 2px solid blue;
width: 200px;
height: 200px;
margin-left: auto;
margin-right: auto;
margin-top: 40px;
}
.gridElement {
display: inline-block;
vertical-align: top;
border: 1px solid black;
}
#textContainer {
margin-left: auto;
margin-right: auto;
}
.chooseButton {
display: inline-block;
}
<!DOCTYPE>
<!DOCTYPE html>
<html>
<head>
<!-- INITIALIZE -->
<link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Black+Ops+One" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://use.fontawesome.com/ca5f7b6f9a.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="stylesheet.css">
<script src="script.js"></script>
<!--CONTENT-->
<title>TicTacToe</title>
</head>
<body>
<div id="textContainer">
</div>
<div id="gridContainer">
</div>
</body>
</html>
As Bamar said, Javascript web applications are event-driven, meaning you need to create event handlers for user interactions with the web page. Events occur when the user interacts with the browser (clicks an element on the page, scrolls the view, etc.). Event handlers are Javascript functions. When binding event handlers, you should only bind them once to an event type. There are only two events in your application that need handling: choosing X or O, and clicking on a square in the grid.
I refactored your code to illustrate a better approach. The choosing of sides is bound once in initGame, and the grid-square-click is bound to the squares when they are created (each time the game is reset by choosing sides again). Note that it is necessary to bind the square click handler again each time the game is reset, because the previous gridElements are removed at the top of resetGrid, and the event handler binding to those removed elements is lost.
$(document).ready(function() {
initGame();
});
var playerSelect, aiSelect = "";
var turn;
var gameOn;
function initGame() {
$('#textContainer').html('<p> Choose Side: </p> <div class="chooseButton">X</div> <div class="chooseButton">O</div>');
$('.chooseButton').click(function(){
playerSelect = $(this).html();
if(playerSelect == "X"){
aiSelect = "O";
} else {
aiSelect = "X";
}
resetGame();
});
}
function resetGame(){
gameOn = true;
turn = "player";
resetGrid();
}
function resetGrid(){
// remove any existing grid elements
$('.gridElement').remove();
for(var i = 0; i < 9; i++){
$('#gridContainer').append('<div class="gridElement"></div>');
}
var gridElementSize = $('#gridContainer').width()/3;
$('.gridElement').css({'width': gridElementSize, "height": gridElementSize});
// bind the click handler to the new elements
$('.gridElement').click(function(e){ // e is the event
handlePlayerClick(e);
});
}
function checkForWinOrDraw() {
// check for win or draw
gameOn = true; // set to false if game is over
}
function handlePlayerClick(e) { // e is the click event
if( gameOn == false ) {
// the current game is over, so do nothing
return;
}
if(turn == "player"){
square = $(e.target);
if( square.html() == "") { // if the square is empty
$(e.target).html(playerSelect); // e.target is the grid element
turn = "enemy";
console.log("Player has made a move");
// the player has made a move
checkForWinOrDraw();
makeEnemyMove();
} else {
console.log("Square has already been taken.");
}
} else {
console.log("Player can't play. It's the enemy's turn");
}
}
function makeEnemyMove() {
if( gameOn == false ) {
// the current game is over, so do nothing
return;
}
// dumb AI picks first empty square. Replace with smart AI
els = $('.gridElement').toArray();
var i;
for( i = 0; i < els.length; i++ ) {
var el = $(els[i]);
if( el.html() == "" ) {
el.html(aiSelect);
console.log("Enemy has made a move");
turn = "player";
break;
}
}
checkForWinOrDraw();
}
#gridContainer{
border: 2px solid blue;
width: 200px;
height: 200px;
margin-left: auto;
margin-right: auto;
margin-top: 40px;
}
.gridElement{
display: inline-block;
vertical-align:middle;
text-align: center;
padding-top: 20px;
border: 1px solid black;
}
#textContainer{
margin-left: auto;
margin-right: auto;
}
.chooseButton{
display: inline-block;
}
<!DOCTYPE>
<!DOCTYPE html>
<html>
<head>
<!-- INITIALIZE -->
<link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Black+Ops+One" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://use.fontawesome.com/ca5f7b6f9a.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="stylesheet.css">
<script src="script.js"></script>
<!--CONTENT-->
<title>TicTacToe</title>
</head>
<body>
<div id="textContainer">
</div>
<div id="gridContainer">
</div>
</body>
</html>

Categories