**I already fixed the problem, but I want to understand how it works (just for curiosity). I've been searching about this problem for long time and I didn't found the right source of information about this. Don't give me external links to 1990 websites, please. **
So basically, I wanted to call a function when user clicks enter button. I wanted to pass information about which button was pressed (in my HTML) to my function in external script.js file and check if it was button "Enter", so my program can proceed to next instructions. And i found something called Event Accesing and it did work actually, but explanation was so horrible that It works but i don't know why. Here's the code.
function myFunction(e) {
if (e.keyCode == 13) {
alert('It works!');
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>To-do list</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="entryText">
<h1>Good evening!</h1>
<h2>This is to-do list app written in plain javascript :)</h2>
<h2>Type your task and click enter on your keyboard</h2>
</div>
<div id="input-container">
<input type="text" id="type_here" placeholder="New task here.." onkeydown="myFunction(event);">
</div>
<script src="js/script.js" defer></script>
</body>
</html>
Michal while your script.js file is external to the HTML document when you include the script tag before you are importing the entire script.js code into the HTML document. So it is fair to say that this example below is how the browser will interpret the code (you could even write it like this):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>To-do list</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="entryText">
<h1>Good evening!</h1>
<h2>This is to-do list app written in plain javascript :)</h2>
<h2>Type your task and click enter on your keyboard</h2>
</div>
<div id="input-container">
<input type="text" id="type_here" placeholder="New task here.." onkeydown="myFunction(event);">
</div>
<script>
function myFunction(e) {
if (e.keyCode == 13) {
alert('It works!');
}
}
</script>
</body>
</html>
The code myFunction(e) take a single parameter in your case you have used the letter 'e' to show that your function takes one parameter. We tend to use something that indicates what we're expecting to be passed to a function, in this case we are expecting and 'event', some people would write the function like this
myFunction(event)
myFunction(e)
Both 1 and 2 are the same but it's generally accepted in the programming community that 'e' stands for 'event' - when you're typing out code all day long it makes sense to shorted and abbreviate words so you can code faster, you could put anything you want like:
myFunction(thing)
...but that's not very helpful if you're someone trying to read someones code, where as 'e' or 'event' is descriptive enough to know that the function wants to be passed an 'event'.
On your line of code:
<input type="text" id="type_here" placeholder="New task here.." onkeydown="myFunction(event);">
you have:
onkeydown="myFunction(event);"
the 'onkeydown' part will fire every time a key is pressed, when a key is pressed it will emit an 'event' with lots of information including the key that was pressed. Your code is saying - when someone presses a key pass that information (the event) onto myFunction(event).
You could re-write the line of code like this:
<input type="text" id="type_here" placeholder="New task here.." onkeydown="myFunction(theInformationFromTheOnkeydownEvent);">
...the string 'theInformationFromTheOnkeydownEvent' isn't the actual 'event' information, it's just some word(s) we've chosen to show that something is being passed to the myFunction function, onkeydown will pass the event information to the myFunction because we've included some text between the parenthesis. If we didn't put anything between the parenthesis then the onkeydown would not pass any information to the myFunction() because we've explicitly told it not to by omitting text like this: myFunction()
Imagine:
onkeydown="myFunction(passTheOnkeydownEventOnToMyFunction)" <- passed info onto myFunction
onkeydown="myFunction()" <- does not pass any information onto myFunction
...the words inside the parenthesis in this case don't matter because the onkeydown is a DOM function (yes it's a function, and it returns event information) so when it's called it will return event information to what ever you want it to, in your case it's returning it to your myFunction.
When you look at your script.js file and the myFunction code you decided to put 'e' inside the parenthesis, you could have chosen 'event' or 'eventData'. The only important thing is that you use the same string throughout your myFunction code block, the three example below work the same and would work with your HTML code I've just changed the 'words' between the parenthesis (some are more descriptive than others):
function myFunction(e) {
if (e.keyCode == 13) {
alert('It works!');
}
}
function myFunction(event) {
if (event.keyCode == 13) {
alert('It works!');
}
}
function myFunction(thing) {
if (thing.keyCode == 13) {
alert('It works!');
}
}
function myFunction(eventData) {
if (eventData.keyCode == 13) {
alert('It works!');
}
}
I hope that makes things a little clearer?
You have attached onkeydown event listener on the input field. So, whenever a key is being pressed, your myFunction function is called with event data.
Such keyDown events carry a keyCode property and each key on keyboard has a unique JS keyCode. You can find the mapping over here. For enter key, key code is 13.
Related
I have explicitly defined a Javascript file for my HTML document. In my HTML, I have created a text box where the user can type in their name, then click a button called "submit."
In JS, as soon as they click "submit," I want to store what they have entered as their name in a variable (I'm using eventListener to know when they click "submit"). My question is, how would I be able to do this without using onclick in my HTML doc? Here is my following code at the moment:
my_button.addEventListener('click', my_function);
function my_function(){
alert("Hello world!");
}
One way would be to use oninput event and every time the user types in something update the variable in which you want to store the input. The input tag would look like this: <input type="text" oninput="myFunction()"> and in the function that is declared as the handler you can take the input and store wherever you want.
You can have the code separate. All you'd have to do in the HTML document is to load the javascript file.
Here's a snippet. First the content of the javascript file, and below the simplified HTML document.
let myButton = document.getElementById("theButton");
myButton.addEventListener('click', my_function);
function my_function(){
alert("Hello world!");
}
<button id="theButton">Test</button>
to add a separate javascript file do this anywhere in your html
<script type='text/javascript' src = 'path/filename' > </script>
to get the value of the input yoy need to slect it first. then you get the value via the value property.
see this example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input id="my_input" type="text">
<button id="my_btn">click</button>
</body>
</html>
then you can use the following javascript.
var my_button = document.querySelector('#my_btn');
var my_input = document.querySelector('#my_input');
var value;
my_button.addEventListener('click',function () {
value = my_input.value;
alert(value);
})
hope this helps!
Please have a look at the below code.
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//cdnjs.cloudflare.com/ajax/libs/annyang/1.1.0/annyang.min.js"></script>
<script>
if (annyang) {
// Let's define our first command. First the text we expect, and then the function it should call
var commands = {
'hello': function() {
alert("Hello!");
}
};
// Add our commands to annyang
annyang.addCommands(commands);
// Start listening. You can call this here, or attach this call to an event, button, etc.
// annyang.start();
}
</script>
</head>
<body>
<div>TODO write content</div>
<button onclick="annyang.start();">Start</button>
</body>
</html>
The JavaScript code sends the data to a external server and get the response. The imported JS file can be found from here - https://github.com/TalAter/annyang
My question is, how can I view the "response" which I get from the server?
To see the results returned in the console, turn on debug mode by adding this:
annyang.debug();
Alternatively, to capture all recognized text in a function, simply add a catch-all function
annyang.addCommands({
'*transcript': function(transcript) {
console.log(transcript);
}
});
P.S. I think you want to uncomment your start() command.
This isn't something I really want to do, just wondering if it's possible.
Say I have a page like this, which is just a heading and an input box.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>2014-4-24-01</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function jQuerySetup() {
if($) {
$(document).ready( function () {
$("body").on("keypress", "input", function ( event ){
if(event.keyCode == 13){
$("body").get(0).innerHTML = this.value;
}
});
});
} else {
window.setTimeout(jQuerySetup, 250);
}
}
jQuerySetup();
</script>
</head>
<body>
<h3>Test</h3>
<input type="text" width="20">
<div id="testDiv"></div>
</body>
</html>
If I type the following into the input box and hit enter, nothing happens. Why is that?
<script>window.setTimeout(function () { alert("Uh oh"); }, 1000);</script>
EDIT: And I know that it's very easy for someone to run JavaScript through the console window and achieve a similar effect. But my question is more of understanding why the above isn't possible (or why I'm not getting it right).
innerHTML won't execute the script, use jQuery html instead.
$("body").html(this.value);
It is possible to run script from an input box using eval(). The way you are doing it won't work since the specification states that scripts inserted via .innerHTML should not be executed (it's a large green note at the end of the section).
From the w3c spec...
Note: script elements inserted using innerHTML do not execute when they are inserted.
Instead just use eval
You don't need if($) { and setTimeout because it's handled by $(document).ready.
You can try that:
<script>
$(document).ready( function () {
$("body").on("keypress", "input", function ( event ){
if(event.keyCode == 13){
$("body").get(0).innerHTML = this.value;
}
});
});
</script>
Working example here
I think I just need a second pair of eyes on this one. The div's onclick event doesn't seem to be working. Any ideas?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title="My First Program"/>
<script type="text/javascript">
window.onload = function(){
window.alert("If you see me then the page has loaded");
click();
}
//we do programming here
/*because
it is
fun*/
window.alert("Helo World!");
function click(){
window.alert("CLICK!!!!");
}
</script>
</head>
<body>
<div>This web page will run my first program</div>
<!--this will be awesome-->
<br>
<br>
<br>
<div id="d1" onclick="click()">Click me</div>
</body>
Also, for the reccord, this is not my first program.
your html is malformed. the title tag needs to look like this:
<title>My First Program</title>
Also, you seem to have a naming conflict because you named your function the same thing as a built-in function. rename your 'click' function to 'myclick' or something else.
Once you fix that, everything else should be good.
When something is going weird, the first thing you should always do is validate your markup.
http://validator.w3.org/check
Here is the complete, working version of the markup.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My First Program</title>
<script type="text/javascript">
window.onload = function(){
window.alert("If you see me then the page has loaded");
click();
}
//we do programming here
/*because
it is
fun*/
window.alert("Helo World!");
function myclick(){
window.alert("CLICK!!!!");
}
</script>
</head>
<body>
<div>This web page will run my first program</div>
<!--this will be awesome-->
<br>
<br>
<br>
<div id="d1" onclick="myclick()">Click me</div>
</body>
Every time I see a question like this anywhere, the typical answer I give is "don't use the Netscape model for event handling".
Give this a read - http://www.quirksmode.org/js/introevents.html
Update: Looks like "click" isn't a very good name for a function, since it's already registered for events and such, which is likely why it didn't work. I should have caught that.
I'm trying to ignore Ctrl-C in my website but im stuck.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script language="javascript">
function whichButton(event)
{
if (event.button==2)//RIGHT CLICK
{
alert("Not Allow Right Click!");
}
}
function noCTRL(e)
{
var code = (document.all) ? event.keyCode:e.which;
var msg = "Sorry, this functionality is disabled.";
if (parseInt(code)==17) //CTRL
{
alert(msg);
window.event.returnValue = false;
}
}
</script>
</head>
<body>
<form method="">
<strong>Not Allow Paste </strong><BR>
<input type="text" value="" onMouseDown="whichButton(event)" onKeyDown="return noCTRL(event)"/>
</form>
</body>
</html>
I tried this code, but it is can only ignore right click.
How can I ignore Ctrl-C?
Have a look at this website
But if someone wants to copy your content, they can. It will just make it harder and more time consuming to use.
And also
Regarding this Ctrl-C you could add javascript to block it, but it is useless, since the user can always disable javascript. In fact many users will find interception of right-click very annoying.
All these could have a meaning if you are building an intranet application or you can ship an integrated browser for users to view the application. With public html, I believe it isn't even worth trying. One solution would be to build your application with flash or another plug-in. This way you can encrypt everything you've sent to the client.
if your body tag adds these events
<body oncontextmenu="return noMenu();" onkeydown="return noKeys(event);">
and you then define these functions in your <head> section, you can take action when the context menu is activated (right click) or when keys are pressed on your page.
<script type="text/javascript">
function noMenu()
{
alert("Not Allow Right Click!");
return false;
}
function noKeys(event)
{
if (event == null) event = window.event;
// here you can check event.keyCode
return false;
}
</script>