Color change only after key press - javascript

So I have a page when you enter a HEX and it'll change to that background. The issue is, you need to press space first for some reason. My question is how can I have it so that then on the initial load, you can just enter it without pressing space? Here's my code for the background change with input
$('.hex').keyup(function(){
var a = $(this).val();
$('#example').text(a);
console.log(a);
$('body').css('background', '#'+a);
});
Here's a demo. Enter a hex in the first box. Nothing will happen, Then press space and enter another hex.

You need to place the onkeyup event handler registering code outside the onkeydown event handler.
Here is the code in onkeydown event handler:
$(document).keydown(function(e) {
if (e.keyCode == '32') {
//...
//you placed the onkeyup event handler registering code here
//which is wrong
}
}
//you should place the code here
$('.hex').keyup(function(){
var a = $(this).val();
$('#example').text(a);
console.log(a);
$('body').css('background', '#'+a);
});
Updated demo.

It's because everithing is in if statement where it checks for if (e.keyCode == '32') and keyCode==32 is space.

Related

js - trigger generic function on space bar press anywhere on document

I have a colour guessing game with six different colour squares and an rgb code at the top of the page. The game works and the game resets via function - resetUI() - when a reset button on the page is clicked.
However, I want to trigger the resetUI function whenever the space bar is pressed. I have the following code, it doesn't throw any errors but it also doesn't work:
var body = document.querySelector("body");
body.addEventListener("keydown",function(){
if(this.key === " "){
resetUI();
}
});
I am fairly certain my use of "this" is wrong but I can't think of an alternative.
I have searched MDN and stackOverflow but I haven't seen a solution to this problem. Thanks.
key belongs to the event (which is passed into the event handler), not the body (which is what this refers to).
The next problem you will have is when you add an input or textarea to the page and anytime the user put a space into the input it will run your function.. You can check against the target to make sure the input isn't receiving the keystroke before you fire your function..
var body = document.querySelector("body");
body.addEventListener("keydown",function(e){
var isInput = ~["TEXTAREA", "INPUT"].indexOf(e.target.tagName);
if(e.key === " " && !isInput){
// resetUI();
console.log("u clicked spacebar, and it wasn't in an input");
}
});
<input />
You have lot of unnecessary code. And you should receive the event object from callback function to check against which key got pressed.
To check spacebar you shouldn't check against " " instead you have to check the keyCode of event.
document.body.onkeydown = function(e){
if(e.keyCode == 32){
console.log("space bar pressed");
resetUI();
}
}

How to clear a textarea value in jQuery?

I'm trying to validate keycode entry by adding an alert when a user types a key that isn't expected, and then clearing the text area. The alert functions correctly but the text area isn't clearing.
I've checked the documentation here, but I can't see an area with my .val() line. I've also tried this: $("#noteNumberInput").attr('value', "");
Scenario: I type 1-9 in the text box and get no alert (works fine), if I type a letter a-z for example, the alert pops up but the letter remains in the text box.
EDIT:
Something I've noticed is that it does clear the textarea after the first key. If I type the letter 'a' and then 'b', the 'a' is removed and replaced with a 'b'.
HTML:
<textarea id="noteNumberInput" placeholder="Note number"></textarea>
JS:
var noteNumberInput = document.getElementById("noteNumberInput");
//VALIDATE NOTE NUMBER TEXTAREA
function validate(key) {
var keycode = (key.which) ? key.which : key.keyCode;
//comparing pressed keycodes
if (keycode === 8 || (keycode >= 48 && keycode <= 57)) {
return true;
}
if (keycode < 48 || keycode > 57) {
alert("Please only enter the note number e.g. 1, 2..14 etc.");
$("#noteNumberInput").val("");
return false;
}
}
noteNumberInput.addEventListener("keydown", validate);
When you do $("#noteNumberInput").val('');, it removes all the content of the textarea, so if that's not what is happening, the problem is probably somewhere else.
Change noteNumberInput.addEventListener("keydown", validate); to use keyup
Using $("#noteNumberInput").val() will clear the textarea
EDIT
The problem is the keydown handler. In this case the function will be triggered followed by the display of alert & then the text area will be populated. But on using keyup the function will be triggered on release of the key.So by that time the textarea will be populated with value.
Change the keydown to keyup
var noteNumberInput = document.getElementById("noteNumberInput");
noteNumberInput.addEventListener("keyup", validate);
DEMO
Your only asking for the validate() function to actually execute when you've pressed the next key.
I think that´s not the best idea to trigger key events, because cut and paste and drag and drop can also change the input element.
try this:
Element.addEventListener('input', function(){
this.value=this.value.replace(/[^0-9,.]/g, '');
});
this must be adapted to textarea...

Press the enter key in a text box with jQuery

How can I mimic pressing the enter button from within a <input>, using jQuery?
In other words, when a <input> (type text) is in focus and you press enter, a certain event is triggered. How can I trigger that event with jQuery?
There is no form being submitted, so .submit() won't work
EDIT
Okay, please listen carefully, because my question is being misinterpreted. I do NOT want to trigger events WHEN the enter button is pressed in textbox. I want to simulate the enter button being pressed inside the textbox, and trigger this from jQuery, from $(document).ready. So no method involving on.('keypress')... or stuff like that is what I'm looking for.
Use keypress then check the keycode
Try this
$('input').on('keypress', function(e) {
var code = e.keyCode || e.which;
if(code==13){
// Enter pressed... do anything here...
}
});
OR
e = jQuery.Event("keypress")
e.which = 13 //choose the one you want
$("#test").keypress(function(){
alert('keypress triggered')
}).trigger(e)
DEMO
Try this:
$('input').trigger(
jQuery.Event('keydown', { which: 13 })
);
try using .trigger() .Docs are here
Instead of using {which:13} try using {keyCode:13}.
$('input').trigger(jQuery.Event('keydown', {keyCode:13}));

Trigger Keypress event of a input field on keypress of another input field?

I have two input fields i want to trigger keypress of one input field on keypress of another input field.
What i have tried is
$('#example').keypress(function(event) {
var press = jQuery.Event("keypress");
var code = event.keyCode || event.which;
press.which = code ;
$('#search').trigger(press);
});
both example and search are input fields. Why i am doing so i because when i enter text in simple field it has to enter text in another field which filters search results.
Try this :
JavaScript
$('#example').on('keypress keyup keydown',function(event) {
// create the event
var press = jQuery.Event(event.type);
var code = event.keyCode || event.which;
press.which = code ;
// trigger
$('#search').val(this.value);
$('#search').trigger(event.type, {'event': press});
});
// Omit - Check if search box reacts
$('#search').on('keypress keyup keydown',function(event) {
// sample
console.log(event.type);
});
Demo here : http://jsbin.com/pebac/1/edit
Note that even if you successfully manage to trigger a keypress event this doesn't act as a real one, meaning that the char won't be appended to the input.
Guess it's like $.click()
$('#search').keypress();
If all you want to do is to copy the content of one field to the other, I'd say it's better to do $('#search').val($(this).val()); instead of triggering the keypress event on #search.

onkeypress on a <a> tag

I'm trying get my <a> tag triggered when the user press on the "enter" key. (onkeypress).
my <a> tag:
<a href="javascript:search()" onkeypress="return runScript(event)">
this is my javascript :
function runScript(e)
{
if (e.keyCode == 13) {
alert("dssd");
return false;
}
}
I dont know whats messed up ?
its work for me
Open in new window using javascript
javaScript
window.runScript = function (e) {
if (e.keyCode == 13) {
alert('ss');
return false;
}
else {
return true;
}
}
window.search = function () {
alert('s');
}
live demo : fiddle
Write your html as given below. Note the property tabindex which makes the a tag focusable in certain browsers.
<a id="link" href="http://google.com" onkeydown="runScript(event)" tabindex="1">I am a link</a>
If you need an autofocus on load, you can use the jQuery function focus as shown below.
$(document).ready(
function(e){
$("#link").focus();
}
);
Then your function
function runScript(e){
if(e.keyCode == 13){
alert("pressed enter key");
}
}
you have to call e.preventDefault(); (or return false in some browsers) if you want to prevent the link load the link in href.
function runScript(e){
e.preventDefault();
if(e.keyCode == 13){
alert("pressed enter key");
}
return false;
}
see a demo here:
http://jsfiddle.net/diode/hfJSn/9/show press enter key when the page is loaded
The ENTER key actually triggers the onclick event:
<a href="#" onclick="alert('hello!');">
This means that your search() function inside the href will execute before the onkeypress event.
That works in my browser, though I suspect it's not the way to achieve what you actually want to do... (maybe?)
Number one, you probably don't want it to "return" anything, so you can just do onkeypress="runScript(e)" and it'll run. If that function does return a value, it's not gonna go anywhere...
Number two, it's kinda rare that a keydown event would fire on an anchor (<a>) element, unless of course the user tabs through the other elements 'till it has focus and then presses a key (usually the browser will "highlight" the element that currently has keyboard focus, if it's not just the whole page). Are you wanting your script to run when someone presses enter after typing in a search box or something? if so, you probably want to listen for the event on the search box itself, so add it as that element's onkeydown attribute (for example: <input id="mySearchBox" onkeydown="runScript(e)">) if you just want it to run whenever the user presses enter, regardless of focus or typing text into any particular field, just do as edmastermind29's comment said and add the event listener to the whole document.
Have you tried adding this to your script?
document.onkeypress = runScript;

Categories

Resources