This code intends to append numbers in a array to the string shown in a div after showing it in another div when one clicks a button. After clicking the button once, the number is shown correctly, but the button can not be clicked twice.
var index = 1;
var chartData = [103, 144, 142, 141]
function update_num(index, l){
console.log(l[index - 1])
document.getElementById('box1').innerHTML = l[index - 1] + ' MU';
setTimeout(function(){
document.getElementById('box1').innerHTML = ' ';
}, 1000);
setTimeout(function(){
document.getElementById('canvas').innerHTML = document.getElementById('canvas').innerHTML + ' ' + l[index - 1];
}, 1000);
}
function func_num() {
var index = 1;
/*Define what should happen after the button is clicked*/
document.getElementById("b").onclick = function(){
var buttonB = document.getElementById('b');
buttonB.disabled = true;
if(index <= 2 ){
update_num(index, chartData);
if(index == 1){
buttonB.innerHTML = 'Next Draw';
buttonB.style.left ='405px';
}
index++;
setTimeout(function(){
buttonB.disabled = false;
console.log('aaa ' + buttonB.disabled);
}, 1000);
} else if (index == 3){
while (index < chartData.length){
setTimeout(function(){update_num(index, chartData);}, 2000 * (index - manualClicks));
index ++;
}
setTimeout(function(){buttonB.disabled = false;}, 1000);
buttonB.innerHTML = 'To Task';
}else{
buttonB.style.visibility="hidden";
}
console.log('run6661' + buttonB.disabled);
if(index == 3 ){
setTimeout(function(){buttonB.innerHTML = 'Automatically Draw for {{ machine_cl }} times';}, forceToLookTime);
}
};
}
func_num();
<div id='canvas' style='position:relative;width:1305px;height:420px; margin: auto; margin-top: 20px;'>
<div>
<button id='b' type='button' style='visibility: visible; position: relative; left: 440px; top: 350px;'>Start</button>
<div id='box1' style='visibility: visible; position: relative; top: 300px; left: 40px; text-align: center;' >
</div>
From SPEC:
2.4.2. Boolean attributes
A number of attributes are boolean attributes. The presence of a
boolean attribute on an element represents the true value, and the
absence of the attribute represents the false value.
Also:
The values "true" and "false" are not allowed on boolean attributes.
To represent a false value, the attribute has to be omitted
altogether.
That said, you MUST remove explicitly the attribute, like this:
document.getElementById('my_button').removeAttribute("disabled");
Your Javascript code is totally fine, the problem is in the markup. You're opening the <div> tag, but not closing it properly, like </div>.
Change
<div id='canvas' style='position:relative;width:1305px;height:420px; margin:auto; margin-top: 20px;'>
<div>
to
<div id='canvas' style='position:relative;width:1305px;height:420px; margin:auto; margin-top: 20px;'>
</div>
Related
I have a variable count that triggers a function positiveBar if the value of count is > 0. If the value of count is < 0, it triggers a function negativeBar.
positiveBar changes a div's position using
progressBar.style.left = '50%';
negativeBar changes that same div's position using
progressBar.style.right = '50%';
This gives me the result I want; however, if at any point count becomes greater than 0, the positioning on negativeBar stops working, and it uses the positioning of the positiveBar function instead.
Video to explain:
var count = 0;
// Show count on the page
document.getElementById("countDisplay").innerHTML = count;
// Update count
function updateDisplay() {
countDisplay.innerHTML = count;
};
// Change negative count to an absolute
function absCount() {
return Math.abs(count);
};
function positiveBar() {
progressBar.style.backgroundColor = "#77eb90";
progressBar.style.width = (count * 10) + 'px';
progressBar.style.left = '50%';
};
function negativeBar() {
progressBar.style.backgroundColor = "#ef5c3f";
progressBar.style.width = (absCount() * 10) + 'px';
progressBar.style.right = '50%';
};
// Count up and down when + and - buttons are clicked and edit bar
add1.addEventListener("click", () => {
count++;
updateDisplay();
if (count > 0) {
positiveBar();
} else {
negativeBar();
}
});
subtract1.addEventListener("click", () => {
count--;
updateDisplay();
if (count > 0) {
positiveBar();
} else {
negativeBar();
}
});
.progressBar__Container {
height: 10px;
margin: 20px auto;
border: 1px solid black;
position: relative;
}
#progressBar {
height: 10px;
width: 0;
position: absolute;
}
<div id="countDisplay"></div>
<button id="add1">+</button>
<button id="subtract1">-</button>
<div class="progressBar__Container">
<div id="progressBar"> </div>
</div>
I tried reordering statements. I also tried creating a condition for if count = 0, but that didn't change the result. I'm very confused because it initially works how I intend, but if count becomes greater than 0 at any point, progressBar.style.right = '50%'; stops being applied.
You aren't clearing any previously set left or right styles when you switch from negative to positive and vice versa.
I would use CSS classes to control the position and colour as it's easier to toggle them based on the state of count.
let count = 0;
const countDisplay = document.getElementById("countDisplay");
const progressBar = document.getElementById("progressBar");
// Update count
function updateDisplay() {
countDisplay.textContent = count;
progressBar.style.width = `${absCount() * 10}px`;
progressBar.classList.toggle("positive", count > 0);
progressBar.classList.toggle("negative", count < 0);
};
// Change negative count to an absolute
function absCount() {
return Math.abs(count);
};
// Count up and down when + and - buttons are clicked and edit bar
add1.addEventListener("click", () => {
count++;
updateDisplay();
});
subtract1.addEventListener("click", () => {
count--;
updateDisplay();
});
.progressBar__Container {
height: 10px;
margin: 20px auto;
border: 1px solid black;
position: relative;
}
#progressBar {
height: 10px;
width: 0;
position: absolute;
}
#progressBar.positive {
background-color: #77eb90;
left: 50%;
}
#progressBar.negative {
background-color: #ef5c3f;
right: 50%;
}
<div id="countDisplay">0</div>
<button id="add1">+</button>
<button id="subtract1">-</button>
<div class="progressBar__Container">
<div id="progressBar"> </div>
</div>
See MDN:
When both left and right are defined, if not prevented from doing so by other properties, the element will stretch to satisfy both. If the element cannot stretch to satisfy both — for example, if a width is declared — the position of the element is over-constrained. When this is the case, the left value has precedence when the container is left-to-right; the right value has precedence when the container is right-to-left.
Because you are setting style.left when you then come to set style.right the above applies - i.e. the style.right setting will get overridden.
how to make a stimulus (image, div, whichever's easiest) show up on right or left half of screen randomly using javascript.
Any ideas about having the button clicks record the reaction time, which button is clicked (left or right), and which side the stimulus was presented on?? Also, the left button should be "true" when stimulus is presented on the right and vice versa.
<head>
<style >
.divStyleLeft {
width: 300px;
height: 300px;
background-color: lightblue;
float: left;
}
.divStyleRight {
width: 300px;
height: 300px;
background-color: lightgreen;
float: right;
}
.maxWidth {
width: 100%;
}
.button {
float: right;
}
.button2 {
float: left;
}
</style>
</head>
<body onload="presentStimulus()">
<div class="button">
<button onclick="presentStimulus()">Click Me</button>
</div>
<div class="button2">
<button onclick="presentStimulus()">Click Me </button>
</div>
<div class="maxwidth"></div>
<div id="float" class="divStyleLeft" onclick="recordClick()">
I AM NOT FLOATING
</div>
<script>
let numClicks= 0;
let timeStart = 0;
let timeEnd = 0;
function Trial(trialTime, sidePresented,buttonClicked,) {
this.trialTime = trialTime;
this.sidePresented= sidePresented;
this.buttonClicked= buttonClicked;
}
let allTrials = [];
for(x = 0; x < 12; x++)
allTrials.push(new Trial(0,0,0));
Trial.prototype.toString=function(){
return this.trialTime + "ms, Side : " + this.sidePresented + ", Reaction Time: " + this.buttonClicked
+ "<br>";
};
function presentStimulus() {
const elem = document.querySelector ( '#float' );
const min = 1;
const max = 2;
const v = Math.floor(Math.random() * (max - min + 1)) + min;
console.log ( 'Random num is ' + v + ": ", '1 will go left, 2 will go right' );
v === 1 ?
( () => {
elem.classList = [ 'divStyleLeft' ];
elem.innerText = 'Hello!';
} ) () :
( () =>{
elem.classList = [ 'divStyleRight' ];
elem.innerText = 'Hi!';
} ) ();
}
function recordClick()
{
let theData = document.getElementById("#float").data;
timeEnd = Date.now();
allTrials[numClicks].trialTime = timeEnd - timeStart;
allTrials[numClicks].sidePresented = theData.sidePresented;
allTrials[numClicks].buttonClicked = theData.buttonClicked;
if (numClicks < 11) {
numClicks++;
presentStimulus();
}
else {
document.getElementById("float").style.visibility = "hidden";
let output = "";
for (x = 0; x < allTrials.length; x++)
output = output + "<b>:" + (x + 1) + "</b>:" + allTrials[x].toString();
document.getElementById("display").innerHTML = output;
}
}
</script>
<p id="display"></p>
</body>
There's a bunch of ways you could go about this.
If you're using plain 'ol JS, I'd probably create classes in CSS that float left or right, possibly appear as a flex container that displays left or right, whatever your specific need might be (again, there's a lot of ways to go about it, and one might be better than the other given your context).
When you've determined left or right (gen a random number or whatever), update the classlist on the DOM elements with the desired class to make it go this way or that.
For what it's worth, here's a bare-bones vanilla JS example. Again, I don't know your specific context, but this should give you a start on how to look at it. Floating may not be ideal, you may want to just hide/show containers that already exist on the left or right or actually create whole new DIVs and insert them into known "holder" containers (usually just empty divs), but the idea is the same; gen the random number, alter the classlists of the elements you want to hide/show/move/whatever, and if necessary, alter the innerHTML or text as needed.
<html>
<head>
<style>
.divStyleLeft {
width: 300px;
height: 300px;
background-color: lightblue;
float: left;
}
.divStyleRight {
width: 300px;
height: 300px;
background-color: lightgreen;
float: right;
}
.maxWidth {
width: 100%;
}
</style>
</head>
<body>
<button onclick="onClick()">Click Me</button>
<div class="maxwidth">
<div id="floater" class="divStyleLeft">
I AM NOT FLOATING
</div>
<div>
<script>
function onClick () {
const elem = document.querySelector ( '#floater' );
const min = 1;
const max = 2;
const v = Math.floor(Math.random() * (max - min + 1)) + min;
console.log ( 'Random num is ' + v + ": ", '1 will go left, 2 will go right' );
v === 1 ?
( () => {
elem.classList = [ 'divStyleLeft' ];
elem.innerText = 'I am floating LEFT';
} ) () :
( () =>{
elem.classList = [ 'divStyleRight' ];
elem.innerText = 'I am floating RIGHT';
} ) ();
}
</script>
</body>
</html>
I have a few problems that are stopping me from proceeding on my blackjack 21 game. First when I open the site in a browser my aceCard function is invoked which is only supposed to be called if you deal a 1 (an ace card). Below I have written some problems I noticed with my aceCard function.
When You get number 1 in the userArray then you will need to call aceCard(); in the console. Or at least I haven't got this to call automatically.
1.when number 1 is in position 0 in array javascript don't recognize the 1.
2.when number 1 is in position 1 in array aceCard function will work and change value to 1 to 11
3.when number 1 is in position 2 in array it see's value 1 in the array, but it won't change value 1 to 11. if array position 0 = 1 then it won't see position 2 in the array.
Any help would be great, I have no idea why this works differently depending where number 1 is positioned in the userArray.
var userArray = [];
var computerArray = [];
var a = userArray.indexOf(1);
function random_number() {
var randNum = Math.floor(Math.random() * 10 + 1);
return randNum;
}
document.getElementById('dealButton').onclick = function() {
userArray.push(random_number(), random_number());
computerDeal();
computerDeal();
calcTotal(userArray);
showMe(calcComputerTotal(userArray));
//cardMaker ();
//cardMaker ();
//inputMyCardValue ();
//inputMyCardValue ();
cardMaker(random_number());
cardMaker(random_number());
//inputMyCardValueComputer ();
//inputMyCardValueComputer ();
return userArray;
}
document.getElementById('hitButton').onclick = function() {
userArray.push(random_number());
//computerHit();
calcTotal(userArray);
showMe(calcComputerTotal(userArray));
cardMaker(random_number());
//inputMyCardValue ();
//cardMakerComputer ();
//inputMyCardValueComputer ();
return userArray;
}
if (userArray.indexOf(1)) {
aceCard();
}
function aceCard() {
if (userArray.indexOf(1)) {
var numberDesired = parseInt(prompt('You got an Ace card! Do you want it to equal 1 or 11?'));
if (numberDesired === 11) {
var a = userArray.indexOf(1);
userArray[a] = 11;
inputMyCardValue();
calcTotal(userArray);
};
};
}
function stay() {
//have computer try to get closest to 21 as posible
}
/*function cardMaker (number) {
var id = 'card' + ($('#cardTable').children().length + 1);
$("#cardTable").append('<div id="' + id + '" class="cardLook">' + number + '</div>');
}*/
function cardMakerComputer() {
var id = 'cardComputer' + ($('#computerCardValues').children().length + 1);
$("#cardTable").append('<div id="' + id + '" class="cardLook"></div>');
}
function inputMyCardValue() {
card1.innerHTML = userArray[0];
card2.innerHTML = userArray[1];
card3.innerHTML = userArray[2];
card4.innerHTML = userArray[3];
card5.innerHTML = userArray[4];
card6.innerHTML = userArray[5];
}
function cardMaker() {
var id = 'card' + ($('#cardTable').children().length + 1);
$("#cardTable").append('<div id="' + id + '" class="cardLook">' + userArray[$('#cardTable').children().length] + '</div>');
}
inputMyCardValue()
inputMyCardValue()
function inputMyCardValueComputer() {
card10.innerHTML = computerArray[0];
card20.innerHTML = computerArray[1];
card30.innerHTML = computerArray[2];
card40.innerHTML = computerArray[3];
card50.innerHTML = computerArray[4];
card60.innerHTML = computerArray[5];
aceCard();
}
function calcTotal(userArray) {
var total = 0;
for (var i = 0; i < userArray.length; i++) {
total += userArray[i];
}
}
function calcComputerTotal(computerArray) {
var total = 0;
for (var i = 0; i < computerArray.length; i++) {
total += computerArray[i];
}
return total;
}
function showMe(VAL) {
var total = calcComputerTotal(userArray);
total = document.getElementById('out2');
parent = total;
parent.innerHTML = VAL;
}
//Cumputer logic
function computerDeal() {
computerArray.push(random_number(), random_number());
}
/*function computerHit () {
if (calcComputerTotal(computerArray) <= 17) {
computerArray.push(random_number());
}
}*/
//when 1 is in position 0 in array javascript don't reconise the 1.
//when 1 is in position 1 in array aceCard function will work and change value to 1 to 11
//when 1 is in position 2 in array it see's value 1 in the array, but won't change value 1 to 11. if array position 0 = 1 then it won't see position 2 in the array.
body {
background-color: lightgrey;
}
#mainContainer {
margin: 0 auto;
padding: 15px;
}
#cardTable {
height: 240px;
width: 95%;
background-color: green;
border-radius: 5px;
margin: 15px 0 15px 0;
}
#computerCardValues {
height: 240px;
width: 95%;
background-color: green;
border-radius: 5px;
margin: 15px 0 15px 0;
}
#out2 {
margin-bottom: 5px;
}
.cardLook {
border: 1px solid black;
width: 120px;
height: 190px;
border-radius: 5px;
float: left;
margin: 20px;
padding: 5px;
background-color: #fff;
}
#card1,
#card2,
#card3,
#card4,
#card5 {
transform: rotate(180deg);
transform: rotate(0deg);
}
#cardComputer10,
#cardComputer20,
#cardComputer30,
#cardComputer40,
#cardComputer50 {
transform: rotate(180deg);
transform: rotate(0deg);
}
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<div id="mainContainer">
<div id="wrapper">
<div id="out2">My total</div>
<button id="dealButton">Deal</button>
<button id="hitButton">Hit</button>
<button id="stayButton">Stay</button>
<div id="cardTable"></div>
</div>
<div id="computerWrapper">
<div id="computerTotal">Computer Total</div>
<div id="computerCardValues"></div>
</div>
</div>
Heading
You're not using indexOf correctly to test whether an element is in an array. It returns the index if the element is in the array, or -1 if it's not in the array. You can't use it as a boolean, because -1 is truthy -- the only falsey value it returns is when the element is in the first array element, because then it returns the index 0.
So if (userArray.indexof(1)) should be if (userArray.indexOf(1) != -1).
There's also no point in putting
if (userArray.indexOf(1)) {
aceCard();
}
in the top-level of the script. Nothing gets put into userArray until the user starts dealing cards. So you should only do that test in the code that runs when dealing a card.
Okay so this is a bit hard to explain this, but I am trying to make where whenever a number is "spawned" or generated, it fades in instead of just popping up.
Here is the Fiddle that I am trying to do that with. I am using a input tag for the number and a for statement to generate the rest--
for (I = 0; I < $("#input:text").val(); I++) {
N.innerHTML += 1 + I + " "
}
I hope I explained that well enough so people understand!
Append span elements instead of text so that you can easily select elements using selector.
Use setTimeout to make it happen serially using index.
Try this:
var D = document,
In = D.getElementById("input"),
CC = D.getElementById("submit"),
N = D.getElementById("N"),
I;
$(In).keyup(function(Key) {
if (Key.keyCode == 13) {
for (var i = 0; i < $("#input:text").val().length; i++) {
var span = '<span style=\'display:none\'>' + (i + 1) + ' ' + $("#input:text").val()[i] + ' </span>'; //set display of `span` element as `none`
N.innerHTML += span;
}
}
$('#N span').each(function(i) {
setTimeout(function() {
$(this).hide().fadeIn(500);
}.bind(this), (i * 500)); // `.bind()` will pass the outer `this` context in`setTimeout` when handler is invoked
})
});
$(CC).click(function() {
N.innerHTML = "";
});
body {
cursor: default;
outline-width: 0px;
}
#main {
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body>
<div id="main">
<input type="text" id="input" maxlength="3" placeholder="Press submit to clear all" />
<input type="submit" id="submit" />
</div>
<h1 id="N"></h1>
</body>
Fiddle here
The jQuery fadeIn method would make this trivial. But if you want to do this with no libraries you can modify the opacity of the result div in a recursive loop. I modified your fiddle here and included it below. The key points are setting the result div to opacity:0 at start, then recursively calling the "fadeIn" function after your original code has ran. you can tweak the timeout delay and opacity increment to get the desired speed and smoothness of the fade effect.
HTML:
<body>
<div id="main">
<input type="text" id="input" maxlength="3" placeholder="Press submit to clear all" />
<input type="submit" id="clear" />
</div>
<h1 id="N"></h1>
</body>
CSS:
body {
cursor: default;
outline-width: 0px;
}
#main {
text-align: center;
}
#N {
opacity: 0;
}
JavaScript:
var D = document,
In = D.getElementById("input"),
CC = D.getElementById("clear"),
N = D.getElementById("N"),
I,
O = 0;
var fadeIn = function() {
O += 0.05
D.getElementById("N").style.opacity = O;
if (O < 1) {
setTimeout(fadeIn, 100)
}
}
$(In).keyup(function(Key) {
if (Key.keyCode == 13) {
for (I = 0; I < $("#input:text").val(); I++) {
N.innerHTML += 1 + I + " "
}
setTimeout(fadeIn, 100)
}
});
$(CC).click(function() {
N.innerHTML = "";
});
How does citicards.com implement the login ID text box with special mask?
When you type "johndoe" and focus out the textbox becomes "jo***oe"
Is there a HTML5 mask with pattern?
Here is a sample implementation of the desired behaviour using pure javascript. This is just for a sample. You may need to do length check etc before actually using substr
document.querySelector("input#accountName").addEventListener("blur", function() {
var value = this.value;
document.querySelector("#maskedAccountName").textContent=this.value.substr(0,2)+this.value.substr(2,value.length-2).replace(/./g,"*")+this.value.substr(this.value.length-2, this.value.length);
this.style.display = "none";
document.querySelector("#maskedAccountName").style.display = "block";
}, false);
document.querySelector("#maskedAccountName").addEventListener("click", function() {
this.style.display = "none";
document.querySelector("input#accountName").style.display = "block";
document.querySelector("input#accountName").focus();
}, false);
div#maskedAccountName {
border: 1px solid rgba(231, 231, 231, 0.67);
padding: 2px;
display: none;
border-top-style: inset;
-webkit-appearance: textfield;
background-color: white;
width: 120px;
}
<input type="text" id="accountName">
<div id="maskedAccountName">
</div>
The reason why I'm not changing the existing input value is I may not be able to read the original value when accessed inside the form submit. So i've created a hidden div which is shown in place of the original input element. You can style the div to be same as the input element using CSS.
You have to use JS/jQuery. First count how mush letters from start and end you wish to take off, then replace everything else with * and append to fake input field.
You can see that in action here (replace opacity to 0 to completely hide input field, display: none will not work here, because you have to click on input itself):
$(document).ready(function() {
$("#hField").focusin(
function() {
$('#hFieldSp').text($(this).val());
});
$("#hField").focusout(function() {
var start = '';
var end = '';
var value = $(this).val();
var stars = '';
if (value.length < 3) {
return;
}
if (value.length > 6) {
start = value.substring(0, 2);
end = value.substring(value.length - 2);
stars = '*'.repeat(Math.max(1, value.length - 4));
} else {
start = value.substring(0, 1);
end = value.substring(value.length - 1);
stars = '*'.repeat(Math.max(1, value.length - 2));
}
$('#hFieldSp').text(start + stars + end);
});
$(document).on('input paste change', '#hField', function() {
$('#hFieldSp').text($(this).val());
});
});
String.prototype.repeat = function(num) {
return new Array(num + 1).join(this);
}
.wrapper {
float: left;
position: relative;
}
#hField,
#hFieldSp {
width: 100px;
height: 30px;
line-height: 30px;
border: 1px solid #ddd;
}
#hField {
opacity: .2;
position: absolute;
left: 0;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div id="hFieldSp"></div>
<input type="text" id="hField" />
</div>
I would use a dummy input for the display. Then on blur, transfer the value to a hidden input and alter the text in the dummy. You might also want the reverse in place in case the user wants to alter the value: on focus, copy the value from the hidden input to the dummy. Here's a sample, no jQuery required, and if there are less than 5 characters in the input, it will make all *s instead.
var start = 0;
var end = 4;
var dummy_user = document.getElementById("user");
var actual_user = document.getElementById("hidden_user");
dummy_user.addEventListener("blur", function() {
actual_user.value = dummy_user.value;
if (dummy_user.value.length > 4) {
start = 2;
end = dummy_user.value.length - 2;
}
var val = "";
for (var i = 0; i < start; i++) {
val += dummy_user.value[i];
}
for (i = start; i < end; i++) {
val += "*";
}
for (i = end; i < dummy_user.value.length; i++) {
val += dummy_user.value[i];
}
dummy_user.value = val;
});
dummy_user.addEventListener("focus", function() {
this.value = actual_user.value;
});
<form action="">
<input type="text" name="user" id="user">
<input type="hidden" name="hidden_user" id="hidden_user" value="">
<input type="password" name="password">
<input type="submit" value="Sign in">
</form>