How to remove previous eventListener? - javascript

var keyPress = function(){
x = document.querySelector(".textt");
x.addEventListener("keyup", function(event){
var keyp = document.querySelector(".textt").value;
console.log(event);
document.getElementById("submit").addEventListener("click", function(){
create(event);
x.value = "";
})
})
}
var create = function(event){
var out = document.querySelector(".output");
var displa = document.createElement('li');
displa.textContent = "The key Code for " + event.key + " is: " + event.keyCode;
out.appendChild(displa);
}
function clearAll(){
location.reload();
}
<!DOCTYPE html>
<html>
<head>
<title> ASCI </title>
</head>
<body>
<p> Enter any Character </p>
<form>
<input class="textt" type="text" id = "inp" onkeypress="keyPress()">
</form>
<button id="tt" onclick="clearAll()">Clear</button>
<button id="submit">Submit</button>
<ul class="output">
</ul>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
**Output1: First time when I press a key I'm able to get keycode
The key Code for a is: 65
**
**Output2: Second time I press key I'm able to get keycodes but it also gives me output for previous key as well as the 2 times the for the new key pressed
The key Code for a is: 65
The key Code for a is: 65
The key Code for b is: 66
The key Code for b is: 66
**
Can someone help me to resolve this? I only want the output for the new key pressed not previous ones's.

Use
x.onkeyup = null;
Before the x.addEventListener line. It'll clear the previous event listener before assigning the new one.

the previous answer is correct, only if the event handlers were assigned using element.event = function. For the addEventListener method, removeEventListener is required to deal with these.
Usage:
element.removeEventListener("the event", the function you want to remove);
But in your case, you used an anonymous function for the handler. It should be like this.
function myFunc(){
console.log("hello world");
}
element.addEventListener("click", myFunc);
element.removeEventListener("click", myFunc);
// This does not work
myFunc = function(){...};
// This also does not work
element.addEventListener("click", function(){console.log("hello world");});
element.removeEventListener("click", function(){console.log("hello world");});

Related

Listing in Javascript

How can I stop this Javascript code from passing the last number of the iteration to the delete function?
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="lista"></div>
</body>
<script type="application/javascript">
var dados = ['vassoura','lixo','papel'];
function deletar(elemento){
console.log(elemento);
}
function listar(){
var div = document.getElementById('lista');
for(i in dados){
campo = document.createElement("output");
button = document.createElement("button");
button.addEventListener("click",()=>{
deletar(dados[i]);
});
button.innerHTML="deletar";
div.appendChild(campo);
div.appendChild(button);
console.log(i);
campo.value = dados[i]+" ";
console.log(dados[i]);
}
}
listar();
</script>
it is passing the last number corresponding to iteration because when I click on the button the iteration has already been made and finished
Looks like here is a common mistake with a variable scope.
Simplest way is to either use closure or replace for(i in dados) at least with for(let i in dados)
First ,get the length of dados. and check when i = dados_length (last element) then skip that code which you want to skip.

Javascript showing wrong results

HTML code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="score-board.css">
<title>Score Board App</title>
</head>
<body>
<div id="playersscores">
<span id="p1score">0</span><span> To </span> <span id="p2score">0</span>
</div>
<p>Playing to <span id="score">5</span></p>
<input type="field" value="5" ></input>
<button id="p1clicked">Player one</button>
<button id="p2clicked">Player two</button>
<button id="reset">Reset</button>
<script type="text/javascript" src="score-board.js"></script>
</body>
</html>
Javascript is :
Whenever this code is loaded :
var p1result = document.querySelector("#p1score");
var p2result = document.querySelector("#p2score");
var p1clicked = document.querySelector("#p1clicked");
function increment_score (player_result) {
//var score = parseInt(player_result.innerText) + 1;
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
p1clicked.addEventListener("onclick", increment_score(p1result))
Whenever this code is loaded in a browser, the span showing the result for player 1 is showing one directly without clicking on player 1 button. i'm not sure what is wrong with the event listener im using.
The event is click instead of onclick
The event listener should be a reference to the function itself, not the result of a function call (which increments the score by 1)
Inside the function, you can access the button with this:
The code could look like this:
function increment_score() {
var player_result = this;
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
p1clicked.addEventListener('click', increment_score);
Use click event not onclick
You pass result of function not instead reference to function
If you need pass parameters to event handler - you can use bind:
p1clicked.addEventListener("click", increment_score.bind({result: p1result, inc: 1 }) )
p2clicked.addEventListener("click", increment_score.bind({result: p2result, inc: 2 }) )
function increment_score () {
var score = parseInt(this.result.innerText) + this.inc;
this.result.innerText = score;
}
[ https://jsfiddle.net/6vw8ay3x/ ]
You have a couple problems there. First, when calling the addEventListener function, you need to specify just "click", not "onclick". Secondly, when you pass the function to addEventListener, you just want it to be a reference to the function not an actual function call. The following changes will net you the result you are seeking.
function increment_score () {
p1result.innerText = (parseInt(p1result.innerText) + 1).toString();
}
p1clicked.addEventListener("click", increment_score);
But since you want to be able to use the same function for multiple players, then I would suggest adding the "onclick" handler to the HTML which will allow you to pass the element you want to increment. Then your HTML code would look like this:
<button id="p1clicked" onclick="increment_score_with_param(p1result);">Player one</button>
<button id="p2clicked" onclick="increment_score_with_param(p2result);">Player two</button>
and your javascript would be:
var p1result = document.querySelector("#p1score");
var p2result = document.querySelector("#p2score");
var p1clicked = document.querySelector("#p1clicked");
function increment_score_with_param (player_result) {
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
window.onload = function(){
var p1result = document.querySelector('#p1score');
var p2result = document.querySelector('#p2score');
var p1clicked = document.querySelector('#p1clicked');
p1clicked.addEventListener("click", function(e){
e.preventDefault();
p1result.innerText = (parseInt(p1result.innerText) + 1).toString();
});
}

Go to URL if input val == something

So, I've found this JSFiddle example. In JSFiddle works well, the problem is that, even if I search any != from "advogados" (just testing), the browser goes to: http://www.site.com/index.html?procura=teste
No jQuery conflict, no html issue.
Here's JS
$("#procura").on("submit", function(event){
// prevent form from being truely submitted
event.preventDefault();
// get value of text box
name = $("#procura_texto").val();
// compare lower case, as you don't know what they will enter into the field.
if (name.toLowerCase() == "advogados")
{
//redirect the user..
window.location.href = "http://jornalexemplo.com.br/lista%20online/advogados.html";
}
else
{
alert("no redirect..(entered: " + name + ")");
}
});
If your javascript is somewhere in your HTML before your <form> your $("#procura") will be an empty set, so the submit-action won't be bound to anything. Try following code:
<html>
<head>
<script type="text/javascript" src="/path/to/your/jquery.js"></script>
<script type="text/javascript">
$(function() {
// This code will be run if your document is completely
// parsed by the browser, thus all below elements are
// accessible
$('#procura').on('submit', ....);
});
</script>
</head>
<body>
<form id="procura">...</form>
</body>
</html>
$(function() {}) is also known as $(document).ready(function() {}), (documentation)
You aren't defining the variable name. http://jsfiddle.net/zwbRa/59/
var name = $("#procura_texto").val();

innerHTML failing on case

I am making a interactive application with a text field to practice javascript, but I am finding for validation, that the case does not display innerHTML text though the rest of the function loops though. text.innerHTML works in all other cases, am I missing something here?
Javascript
function getNum(input){
if (isNaN(input)) {
oldstate = state-1;
state = 33;
console.log("Loading error Message...");
act();
}
else{return(parseInt(input, 10));}
}
function act(){
console.log("Case: "+state);
input = inputf.value;
inputf.value="";
switch(state){
case 0:
name = input;
text.innerHTML = "Well, hello there, "+name+"! Nice to meet you. What's your age?";
break;
case 1:
text.innerHTML = "Loading...";
age = getNum(input);
text.innerHTML = "So, "+name+" you are "+age+" years old!";
break;
case 33:
text.innerHTML = "That is NOT a number! Hit Submit to Return.";
console.log("Error Successfully loaded!");
state = oldstate;
break;
}
state=+1;
}
function getStr(input){
}
Here is my HTML with the text field id's. Any optimization suggestions would also be appreciated.
HTML
<!DOCTYPE html>
<html>
<head>
<title>titles are lame</title>
<link/>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script type="text/javascript" src="script.js"></script>
<script></script>
</head>
<body>
<div id="wrapper"><div id="text">First, let's have your name.</div>
<br>
<input type='text' id="input"><input type="submit"id="submit" onclick="act()">
</div>
<script>
var state = 0;
var inputf = document.getElementById("input");
var text = document.getElementById('text');
var input, name, age,oldstate;
document.getElementById("input").addEventListener("keydown", function(e) {
// Enter is pressed
if (e.keyCode == 13) { act(); }
}, false);
</script>
</body>
</html>
I think I know what the problem is. In case 1, you call the getNum method, it executes just fine in the correct case, calls the act() method, enters case 33 correctly, returning an error and... then keeps executing case 1. Because you didn't specify a return statement in the first case of the getNum function, age has an undefined value. It should work fine if you add this line:
if (!age) return;
just after calling the getNum method in case 1.
EDIT: I just realized you should also check how state is managed after detecting an error. Adding the line I gave you will leave a state of 33.
Click here to see the answer..
act() //Changed

Bug displaying a div element when a user clicks on a button

I'm writing a webpage and I need to display a div with some content when a user clicks on a button.
I've written the code below and I don't understand why it doesn't work.
Does someone know why ?
My code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso 8859-1" />
<script type="text/javascript">
function traverse(){
output.innerHTML+='Test'; // Nothing happens !
}
function check() {
var keywords = document.getElementById('text').value.split(" ");
for (var i=0; i < keywords.length; ++i) {
traverse_tree()
}
}
</script>
</head>
<body onload ="init()">
<input id="text" type="text" size="60" value="Type your keywords here" />
<input type="button" value="Display the text 'Test'" onclick="check();" />
<div id="output">
</div>
</body>
</html>
thanks,
Bruno
Perhaps because the function is called traverse() and you're calling traverse_tree()?
Also, in your method traverse, you should get the element using document.getElementById('output'), instead of using a (undefined) variable output:
i.e:
function traverse(){
document.getElementById('output').innerHTML+='Test';
}
You could also speed this up by caching the node (to avoid calling getElementById each time the button is clicked):
// Create a closure by wrapping the cached node in a self-executing
// function to avoid polluting the global namespace
var traverse = (function (nodeId) {
// Cache the node to be updated here
var node = document.getElementById(nodeId);
// This is the function that "traverse()" will call. Return this function,
// which will assign it to the variable traverse.
return function () {
node.innerHTML += 'test';
};
// Execute the function with the id of the node to cache, i.e. output
}('output'));

Categories