Javascript Variable Increase - javascript

I am a noob to javascript and and programming really and I just want to know what I am doing wrong. Im sure this is a really simple question but I have no idea why this isn't working. According to research online I'm doing everything correctly.
var varname = 0;
$(document).keydown(function(e) {
if(e.which == 74) {
varname++;
console.log(varname);
}
}
Everytime I press "j" I want to increase my variable, but console log shows a consistent 1 and doesn't go any higher. What can I do Thanks for the help. The key press event works fine, the number just wont increase upon the keypress. Thanks again

you can just declare like this:
var varname = 0;
function keyPress(e){
if(e.which == 74) {
varname++;
console.log(varname);
}
}
In this case, your variable will keep it's previous value, and it will increment.

It's a little hard to tell, but I presume you're trying for something like this:
var jCounter = 0
document.getElementById('keycheck')
.addEventListener('keydown', function (evt) {
if (evt.which === 74) {
console.log("Yup, that's a 'j' alright.")
jCounter++
document.getElementById('jcounter').innerHTML = jCounter
}
})
<input type="text" id="keycheck" placeholder="I really like j's...">
<span id="jcounter">0</span>

Related

How to make one keypress trigger multiple events separately

TL;DR: Each time a user presses the space key, I want the next line of dialogue to appear.
Context: I've just started learning to code in the last few weeks (first basic html & css, now JS). I've mostly been using freecodecamp and YouTube. To help me learn more creatively, I thought I'd start making a little text-based game (BOTW-themed, because it's my favourite actual game). I have all sorts of ideas for things I'd like to implement later, but I'm a bit stuck early on.
The problem: At the beginning of the game, I want to have some lines of dialogue, that I'll .append into the document, each time the user presses the space key. The basic code looks like this:
$(document).keyup(function(e) {
if (e.which == 32) {
$('#gameText').append("<h2>It sounds familiar...</h2>");
}
});
$(document).keyup(function(e1) {
if (e1.which == 32) {
$('#zelda').append("<h3>Link...</h3>");
}
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<h1> You hear an faint, incorporeal voice, carried by the wind... </h1>
<script>
function(e)
</script>
<h2 id="gameText"></h2>
<h3 id="zelda"></h3>
<p> Press <b>space</b> to continue</p>
The problem with that is that a single press of the space key will trigger all the .keyup events at once; whereas I want to bring the lines in one at a time.
I've tried a few different ideas, such as creating a number variable, and incrementing it on each keypress, then using a switch statement to select each line of dialogue.
let spacecount = 0;
while (spacecount < 10) {
$(document).keyup(function(e) {
if (e.which == 32) {
spacecount++;
}
});
switch (spacecount) {
case 1:
$('#gameText').append("<h2>It sounds familiar...</h2>");
break;
case 2:
$('#zelda').append("<h3>Link...</h3>");
break;
}
}
But it's just not happening, and I'm stumped. Apologies for the long-winded post.
This would be a more elegant solution. Instead of huge switch blocks you could have an array (or object) of dialogue lines and a counter to mark your next line.
const dialogue = [
["#gameText", "<h2>It sounds familiar...</h2>"],
["#zelda", "<h3>Link...</h3>"]
];
let counter = 0;
$(document).keyup(function(e) {
if (e.which == 32) {
if (counter >= dialogue.length)
return;
$(dialogue[counter][0]).append(dialogue[counter][1]);
counter++;
}
});
<div id="gameText"></div>
<div id="zelda"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I think putting logic inside event listener should solve the problem:
let spacecount = 0;
$(document).keyup(function(e) {
if (spacecount < 10 && e.which == 32) {
switch (spacecount) {
case 1:
$('#gameText').append("<h2>It sounds familiar...</h2>");
break;
case 2:
$('#zelda').append("<h3>Link...</h3>");
break;
}
spacecount++;
}
});
You are using the same event for executing two functions. jQuery will execute both functions when the button is pressed. You need to set a counter and count the event.

Execute a function on key press if condisions are right

So the problem is... It doesn't work. And more correctly... how can i better execute those nested ifs?
document.body.onkeypress = function(e) {
e = e || window.event;
if (e.keyCode == '38') { //arrow up
}
if (e.keyCode == '40') { //arrow down
if (top == 1) {
window.setTimeout(show2, 100);
alert('2 layer works');
}
if (top == 2) {
window.setTimeout(show3, 100);
}
if (top == 3) {
window.setTimeout(show4, 100);
}
}
}
I've tried everything. Please help me...
Start with this example. It shows how to hook up the keydown event to the document body correctly. From here you should be able to modify it to add the additional logic you have in your example. Be careful to make sure external variables like top are set correctly.
function handleKeyDown(e) {
console.log('got keyDown event. e.keyCode =', e.keyCode)
}
document.body.addEventListener("keydown", handleKeyDown, false);
<p>Press a key</p>
Where do you change the top value...? Also the first if statement, if its blank like you showed us here, will throw in an error, or at least won't do anything. Why do you say e = e || window.event ..? Also, this might be just me, but don't call the functions like that. Better ( again, at least in my opinion ) to do:
document.body.addEventListener("keypress", e => {
// Get rid of that e = e || window.event, I have no clue why you'd do that.
if (e.keyCode == 38) {
// Actually give it some parameters to do here, leaving it empty will either
// throw an error or in "best" case won't do anything.
}
if (e.keyCode == 40) {
// Again, you said you did var top = 1. It will work here.
if (top == 1) {
window.setTimeout(show2, 100);
alert('2 layer works');
}
// But you dont INCREMENT the top variable anywhere, so this wont work.
if (top == 2) {
window.setTimeout(show3, 100);
}
// But you dont INCREMENT the top variable anywhere, so this wont work.
if (top == 3) {
window.setTimeout(show4, 100);
}
}
})
This question is really, really badly formatted and you haven't provided much information. Show us the error you get, use console.log all the time, it's your best friend.

Change variable value on button click

very new to JS, I'm struggling with my current project: Trying to insert some HTML via a function if a variable = "yes". The variable value will change on a button click.
I've been using firebug to look at the variable value - it doesn't seem to be changing on the button click.
Was hoping someone would be kind enough to help.
I THINK my main issue is with setting the variable value - but I could of course be wrong so I've attached a codepen version for good luck :)
HTML:
<button id="butterbutton" onclick="imageAdd('yes'); ">
<img id="worldimg" src="http://butterybeast.hol.es/world.png"></img>
</button>
JS:
var beast
function imageAdd(choice) {
beast = choice;
}
if (beast = "yes" ) {
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
http://codepen.io/Puffincat/pen/Nrdgrz?editors=1010
You have just a couple of problems with your code. The first is this:
if (beast = "yes") {
In this case, you're assigning "yes" to beast, not comparing it. Change it to
if (beast == "yes") {
Next, your code at the bottom (if (beast == "yes") { ...) is only run at the start. Instead, you want that code to run whenever the variable is updated. Move it into your imageAdd function or somewhere else where you update the UI then call it from imageAdd. While you're at it, remove that imagemap function declaration. It doesn't make sense to declare a function inside of an if statement.
var beast;
function imageAdd(choice) {
beast = choice;
updateUI();
}
function updateUI() {
if (beast == "yes") {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
You have a function imagemap wrapped in a conditional but you aren't calling that function.
Also for your conditional, beast will always be null since the conditional is called straight away.
Consider the following adjustment
var beast;
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
function imageAdd(choice) {
beast = choice;
if (beast === "yes" ) {
imagemap();
}
}

JS two if's statement

I wrote a javascript code which if you are browsing with Firefox and if the window is resized to pop up an alert box. However, my knowledge is not enough to see where is the mistake in the code I wrote. If someone can help me I will be really grateful. Thanks in advance.
$('FirefoxChecker').ready(function() {
if (navigator.userAgent.indexOf("Firefox") > 0) && (window.onresize){
alert("Some text here");
};
});
Incorrectly formatting your conditional statement
$('FirefoxChecker').ready(function() {
if (navigator.userAgent.indexOf("Firefox") > 0 && window.onresize){
alert("Some text here");
}//; no semicolon
});
You can have as many conditions as you want in one statement for example
if( condition1 && conditio2 || condition3) { }
Your initial statement was a disconnection between eachother.
if( condition1) && (condition2) {} //is incorrect of course
YET! We can do something like this and what it does is clean the statement up or make the statement more accurate.
//group1 //group2
if( (condition1 && condition2) || (condition3 && condition1) )
1 2 2 3 3 1
I've added numbers below and they correspond to each parenthesis that it belongs to.
As others have said window.onresize is not a testable property, but you get that and hopefully can move forward on that. We can test onresize though like so
if("onresize" in window) {}
window.onresize is an event not property.
Edit: As mentioned by EasyBB in comments, onresize is a property of the window but its in initial value is null unless we define one. It expects a value to be an eventHandler which will be invoked when resize event takes place.
Try this:
window.onresize = function() {
if (navigator.userAgent.indexOf("Firefox") > 0) {
alert("Some text here");
}
};
To invoke something when resize is done, try this:
var timeOut;
window.onresize = function() {
clearTimeout(timeOut);
timeOut = setTimeout(function() {
if (navigator.userAgent.indexOf("Firefox") > 0) {
alert("Some text here");
}
}, 200);
};

Create an autocompleter like the Facebook status update

I'm trying to create a div with contenteditable like the Facebook status update. Then I mean I want to show an autocomplete box when the user have written #.
How would you do that. Currently I'm just playing with keypress and check if the keycode = 64. Somehow that works, but it doesn't validate if there's a space before the alfa, or if the user has unfocused the box, then focused it again.
Any ideas? Or do you know about any plugin that works something like that?
Tnx
I'd probably do it with keypress too.
but we need to check the cursor position to check the character before the '#'.
here's the function I used from http://javascript.nwbox.com/cursor_position/cursor.js
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate();
r.moveEnd('character', o.value.length);
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text);
} else {
return o.selectionStart;
}
}
then with jquery I wrote this keypress callback function:
txt.keypress(function(event) {
if (event.which == 64) {
var index = getSelectionStart(this)
var prevChar = txt.val().substring(index - 1, index);
// now you can check if the previous char was a space
}
});

Categories

Resources