I'm trying to write some code that will print either "Spinning left" or "Spinning right" depending on whether the left or right arrow keys are pressed down. At the moment, it seems to continuously print out the statement until the other key is pressed, and then it will just print the other statement many times instead. Heres my code at the moment :
function Update () {
if(Input.GetKey(KeyCode.LeftArrow)){
print("spinning left");
}
if(Input.GetKey(KeyCode.RightArrow)){
print("Spinning right");
}
}
I originally had "left" instead of KeyCode.LeftArrow, but it didn't change the output. I'm new to Javascript, so is there something that I forgot to do to make the program stop registering that the button is pushed?
I guess he's working in Unity...
use if (Input.GetKeyDown ("left")) instead of KeyCode.LeftArrow
this only prints if you hold down the key...
http://docs.unity3d.com/Documentation/ScriptReference/Input.GetKeyDown.html
Related
This one really has me scratching my head.
I'm building a calculator using JavaScript as an exercise. Said calculator is up and running here on Codepen. In the lower left you will see a "+-" button, which simply takes the content of the input field, and reverses it's sign (positive becomes negative, negative becomes positive.) Then when the user presses an operation button this is pulled and used in the calculation. Simple right?
The function which actually changes the sign is as follows:
function toggleSign() {
if(getCurrentDispVal()[0] === "-") {
currentNumStr = currentNumStr.slice(1, currentNumStr.length);
} else {
currentNumStr = "-" + currentNumStr;
}
updateDisplay(currentNumStr);
}
and is called in just one place, a function which takes input from the user and decides what to do with it:
function useInput(input) {
if(input.match(/(\d|\.)/)) {
handleDigitInput(input);
} else if(input.match(/(X|\/|-|\+)/)) {
handleBinaryOperation(input);
} else if(input.match(/=/)) {
handleEqualsOperation();
} else if(input.match(/^c$/)) {
clearCurrentNumStr();
} else if(input.match(/^ac$/)) {
allClear();
} else if(input.match(/^shorten$/)) {
shortenCurrentNumStr();
} else if(input.match(/^plusmin$/)) {
toggleSign();
}
}
Now sometimes, and only sometimes, this works as expected. For instance, enter the following:
1 on keyboard, not the screen
Click the "+-" button
+ on keyboard
5 on keyboard
enter on keyboard
Sometimes this runs properly, and spits "4" as the result. Sometimes, and this is baffling me, when you hit enter it flips the sign on "5" making it "-5" and then returns "-6" as the answer." I've done some checking and can see that when this occurs, in the useInput function both the /=/ and /^plusmin$/ conditionals are being triggered. Thus toggleSign is being called prior to handleEqualsOperation and this is lousing up the results. Strangely, if you don't use the keyboard, and just click the screen buttons directly, this problem doesn't occur.
I'm at a loss here. There doesn't seem to be any pattern as to when this occurs, and I'm using the same input above over and over. I don't understand why this is occurring, and why it isn't occurring consistently.
So for what I can see, there is a problem in the way you handle the "currentNumStr" variable, follow this example, to find another problem:
press 5
press the +/- button to toggleSign
press the X button
press 6
"It will display -30", but since you made an operation (handleBinaryOperation, handleEqualsOperation) "currentNumStr" will be empty"
press the +/- button to toggleSign
you will get an empty display
If you track this variable you'll get your answer.
Also keep in mind that e.key is not cross-browser compatible, maybe you could use e.keyCode or e.which instead, I got many undefined errors because of this.
EDIT: To exemplify what I added in the comments:
in the HTML change this:
<div class="calc-body>
to this, choose the id you want ( the tabindex is necessary so the div cant get the focus)
<div class="calc-body" id="forFocusId" tabindex="0">
and in the Js file, add a global var to assign the div ( if you dont want to add a variable, you can call document.getElementById("forFocusId") in the next step instead)
var focusElement = document.getElementById("forFocusId");
finally at the end of the function useInput, add
focusElement.focus();
I've noticed from a few different projects of mine that whenever I click something I add an onClick function to, it always takes two clicks to get them going when a page is freshly loaded. The general structure I use for them is:
function PageChange(){
var welc_p = document.getElementById("welcome");/**gathers page DIVs**/
var page01 = document.getElementById("page01");
var page02 = document.getElementById("page02");
var start = document.getElementById("start_btn");/**gathers buttons**/
var p1_back = document.getElementById("p1_back");
var p1_next = document.getElementById("p1_back");
var p2_back = document.getElementById("p2_back");
var p2_next = document.getElementById("p2_back");
start.onclick=function(){
page01.style.display="block";
welc_p.style.display="none";
window.location="#page01";
};
}/**function**/
then the way I call it in the html is
<div class="some_class" id="start_btn" onClick="PageChange()">!!!LETS GET STARTED!!!</div>
Here's a fiddle of it as well.
https://jsfiddle.net/Optiq/42e3juta/
this is generally how I structure it each time I want to create this functionality. I've seen tons of other posts on here about their items taking 2 clicks to activate but none of them were doing anything near what I was trying to accomplish and it seemed their problem was within their coding. Does anybody know why this is happening?
This is because you are attatching a event handler to your button on click of your button.
This means that one click of the button activates the event handler, not the code within start.onclick=function() {
Then, the second click works becasue the event handler has been activated, and now the code will run.
Try moving your code out of the function, then it will work with just one click
Just had the same issue, and found an easy solution based on the above answer.
Since your function needs two clicks to work, I just called the function above the function and it works fine. This way the function already gets called one time on load, then it gets called the second time when you click it.
yourFunction();
function yourFunction(){
-- content --
}
I also had the same 2 clicks required on intitial interaction and after many searches couldn't find the best solution for my specific nav menu. I tried this solution above but couldn't get it to work.
Stumbled upon this code from a youtube example and it solved my issue. I wanted to nest submenu's for multiple levels and modified it from its original implementation to work best for my responsive mobile menu.
var a;
function toggleFirstLevelMobileSubMenu(){
if(a==1){
document.getElementById("mobile-sub-menu-depth-1").style.display="none";
return a=0;
}
else {
document.getElementById("mobile-sub-menu-depth-1").style.display="flex";
return a=1;
}
}
var b;
function toggleSecondLevelMobileSubMenu(){
if(b==1){
document.getElementById("mobile-sub-menu-depth-2").style.display="none";
return b=0;
}
else {
document.getElementById("mobile-sub-menu-depth-2").style.display="flex";
return b=1;
}
}
Of course, in the CSS I had display: none set for both ID's.
First, the problem:- On first click instead of running js your browser runs the button aka the event.
Solution:- in order to resolve this we need to make sure our function is already before the event is run (this is one of the ways to solve the problem). To achive this we need to load the function aka call the function in some way.
So, i just simply called the function after function is completed.
Code answer-
Just add at the end of your code
PageChange();
I have a page with a lot of elements (~1,500) of the same class on it, and when I execute
$(".pickrow").addClass("vis");
it takes a second or two for the page to reflect the changes. So that users aren't thinking the page was stuck, I'd like to pop-up a small message using:
$("#msgDiv").show();
$(".pickrow").addClass("vis");
$("#msgDiv").hide();
But the msgDiv never shows. If I remove the $("#msgDiv").hide(); the msgDiv appears simultaneously with the application of the added class (after the 1 or 2 seconds it took to add the class).
It seems like the jQuery functions get pooled and run together without any screen updates until they have all completed.
How can I get the msgDiv to appear while the $(".pickrow").addClass("vis"); is processing?
Here's a Demo
You probably want to delay the hide by a few seconds.
$("#msgDiv").show();
$(".pickrow").addClass("vis");
setTimeout(function(){ $("#msgDiv").hide(); },2000);
Or using jQuery's animations queue for timing:
$("#msgDiv").show();
$(".pickrow").addClass("vis");
$("#msgDiv").delay(2000).hide(1); //must make it at least 1 ms to go into the queue
You can go with this approach also
Working DEMO
$(document).on("click",".btn",function(){
$(".msg").show("fast",function(){
$(".pickrow").addClass("vis");
var interval = setInterval(function(){
var picLength = $(".pickrow").length;
var visLength = $(".vis").length;
if(picLength == visLength){
clearInterval(interval);
$(".msg").hide();
}
},500);
});
});
I think if you simplify the code, you would find that it is much more responsive and probably not require the loading message. In your code, you check every single element in an if statement. Rather than do that, you can check one value, then update all of them accordingly.
Here's a demo: http://jsfiddle.net/jme11/3A4qU/
I made a single change to your HTML to set the initial value of the input button to "Show Details". Then in the following code, you can just check whether the value is Show Details and remove the class that hides the .pickrow and update the value of the button to be "Hide Details" (which is better feedback for the user anyway). Likewise, you can add the .hid class to the pickrow if the button value is not "Show Details". This will also normalize all of the classes regardless if some were individually hidden or shown.
$('#showhide').on('click', function(){
if ($(this).val() === 'Show Details') {
$('.pickrow').removeClass('hid');
$(this).val('Hide Details');
} else {
$('.pickrow').addClass('hid');
$(this).val('Show Details');
}
});
I have a code to put a wait cursor on all the images when a image is clicked.
function disableButton()
{
idStopSelBtn.style.cursor='wait';
idStartSelBtn.style.cursor='wait';
idBounceRunningBtn.style.cursor='wait';
idStopAllBtn.style.cursor='wait';
idStartAllBtn.style.cursor='wait';
idBounceSelBtn.style.cursor='wait'
}
When the function called by clicking of button gets I designed another function to take away wait cursor and put default cursor.
function enableButton(strType)
{
idStopSelBtn.style.cursor='default';
idStartSelBtn.style.cursor='default';
idBounceRunningBtn.style.cursor='default';
idStopAllBtn.style.cursor='default';
idStartAllBtn.style.cursor='default';
idBounceSelBtn.style.cursor='default';
alert('done');
}
The wait sign is still not going after calling this function. I just added alert to check if the function is firing or not and it's firing, still cursor sign is not changing.
try setting it to auto instead of default:
function enableButton(strType) {
idStopSelBtn.style.cursor='auto';
idStartSelBtn.style.cursor='auto';
idBounceRunningBtn.style.cursor='auto';
idStopAllBtn.style.cursor='auto';
idStartAllBtn.style.cursor='auto';
idBounceSelBtn.style.cursor='auto';
alert('done');
}
This is what you need.
idStopSelBtn.Attributes.Add( "onclick", "document.body.style.cursor = 'wait';" );
Please correct me if I am wrong. I am not a .net developer and I guess this is .net code and our team is doing like this...
I hope it may help...
EDIT it as you want. Instead of putting direct css code there itself call a js function and proceed with default and wait cursor manipulation there.
I want to make a custom made confirmation box in javascipt just like the built in confirm box. the built in confirm box does not allow the code to progress unless the user selects atleast one thing. Below is my code:
*****HTML start*****
<div class = "popUp confirm" style="z-index:40000;" id="confirmBlock">
<div id = "confirmLabel" >Confirm Message</div>
<div style ="border:0px solid red;height:44.56px;">
<input id="Confirm" type="button" value="Confirm" onclick = "confirmAction(1)" />
<input id = "CancelConfirm" type="button" value="Cancel" onclick = "confirmAction(0)" />
</div>
</div>
*****HTML end*****
*****Javascript start*****
var confirmresult = "-1";
function confirmationLoop()
{
alert("If this alert is preesnt it works, seems like the built in alert provides some sort of pause for other parts of code to continue to work");
if(confirmresult == "-1")
confirmationLoop();
return;
}
function confirmAction(val)
{
confirmresult = val;
}
function checkuuu()
{
confirmresult = "1";
}
function confirmMessage(message)
{
document.getElementById("confirmLabel").innerHTML= message;
//var check = setTimeout(function(){confirmAction(1)},5000);
confirmationLoop();
/*
while(1) //using while almost does not allow any other part to run at all hence tried recursion
{
if(confirmresult != "-1")
break;
}
*/
document.getElementById("confirmLabel").innerHTML= "Confirm Message";
var returnVal = confirmresult;
confirmresult = -1;
return returnVal;
}
*****Javascript end*****
*****Sample code start*****
So this i what i expect below:
function example
{
var check = confirmMessage(message);
//the next part of code should not execute untill i press confirm or cancel, using settimeout or settimeinterval is asynchronous and the code flow continues. i want the effect something like alert and confirm built in boxes
}
*****Sample code end*****
I used loop but it keeps the thread completely occupied and does not give me a chance to press any button, which was quite obvious
However recursion gives u the freedom to perform other activities. The problem even though the value of confirmResult will become 1 upon pressing confirm button, which i check through alert. the recursive loop i.e. confirmation loop does not seem read it as 1. it still continues as -1. If i put a alert in that confirmation loop the value wil be read as 1. Can anyone help me to achieve what i started out to??????
P.s.=> sorry for such a huge question!!!
You can't use any sort of loop - as you've found it'll just cause the browser to lock up.
What you need to do is to emulate a "modal" dialog box.
This is usually done by having your dialog box appear on top of another "overlay" element which importantly covers every other element, and prevents any user interaction with them.
It's also pretty hard to implement a confirm function that'll return a value - the window.confirm method can only do that because it's synchronous - it blocks all other JS processing while the dialog is displayed.
The easiest approach is to instead supply a callback function that'll get called once the user has selected the desired value.