What could be causing my JavaScript function to produce repeated letters with just one key press?

After implementing a code that generates different variables based on the 'truth' variable, I encountered an issue. Everything works flawlessly when 'truth' is set to "name," but as soon as I switch it to "email," any keystroke results in duplicate outputs. Any guidance on this matter would be highly appreciated.

var cmd = "";
var cmd1 = "";
var truth = "name";
$(document).ready(function() {
    $("#contactlink a").click(function(){
        $(document).keyup(function(event){
            if (truth == "name"){
                if (event.which == 8){ //backspace deletes last character of string
                    cmd = cmd.substring(0, cmd.length - 1);
                }
                else if (event.which == 13){
                    var name = cmd;
                    $("#emailcontact").typed({
                        strings:["<br/><br/>Email Address: "],
                        typeSpeed: 10,
                        showCursor: false
                    }); 
                    truth = "email";
                }
                else if ((event.which >= 65 && event.which <= 90) || event.which == 32){
                    if (cmd.length == 0){
                        cmd = cmd + String.fromCharCode(event.which);
                    }
                    else if (cmd.substring(cmd.length-1,cmd.length) == " "){
                        cmd = cmd + String.fromCharCode(event.which);
                    }
                    else{
                    cmd = cmd + String.fromCharCode(event.which).toLowerCase();
                            }
                        }
                        $('#namecontact').text(cmd);
                    }
                    else if (truth == "email"){
                        if (event.which == 8){ //backspace deletes last character of string
                            cmd1 = cmd1.substring(0, cmd1.length - 1);
                        }
                        else if (event.which == 13){
                            var name = cmd1;
                            $("#emailcontact").typed({
                                strings:["<br/><br/>Email Address: "],
                                typeSpeed: 10,
                                showCursor: false
                            }); 
                            var cmd2;
                        }
                        else if ((event.which >= 65 && event.which <= 90) || event.which == 32){
                            cmd1 = cmd1 + String.fromCharCode(event.which).toLowerCase();
                        }
                        $('#emailcontact').append(cmd1);
                    }                       
                });
            });
        });

Answer №1

The reason for this behavior is the continuous addition of a new $(document).keyup(...) listener each time the #contactlink a element is clicked.

To remedy this, you can implement the following solution:

 $("#contactlink a").click(function(){
    $(document).off("keyup");
    $(document).on("keyup", function(event){
    });
 });

This approach involves removing the previously attached listener before adding it once more.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving date from timestamp in a node.js environment

Can someone help me figure out how to display my timestamp as the date in the front end? I've tried multiple methods without success. Here is the code snippet: formulaire.addEventListener('submit', posteValidation); /** * Function to add a ...

How can we use JavaScript to retrieve an element with custom styling?

I've encountered a strange issue with my script where it seems to stack up borders and display a 2px border instead of the intended 1px border when switching elements on click. Here is the link code I am using: <li ><a href="plumbing.php"&g ...

Tips for continuing to write to the same CSV file without starting over

Currently, I am utilizing a nodejs package to write data to a CSV file every minute. The initial creation of the file and the first write operation work fine. However, when attempting to write to the same file again, I encounter an error in nodejs. Despite ...

Leverage the Power of Two AngularJS Factories

Can I efficiently use two Factories in AngularJS by calling one from the other? Here's the Scenario: I have a Factory that returns an Array. This Factory is responsible for checking if the data to populate this Array already exists in local SQL Stor ...

Eliminate properties from a TypeScript interface object

After receiving a JSON response and storing it in MongoDB, I noticed that unnecessary fields are also being stored in the database. Is there a way to remove these unnecessary fields? interface Test{ name:string }; const temp :Test = JSON.parse('{ ...

Obtain data from an external XML source using jQuery

Hey there! I'm looking to scrape/parse some information from an external XML file hosted on a different domain and display it on my website. I attempted the following but unfortunately, it didn't work as expected: jQuery(document).ready(functio ...

Next.js 14 useEffect firing twice upon page load

Having an issue with a client component in next js that is calling an API twice at page load using useEffect. Here's the code for the client component: 'use client'; import { useState, useEffect } from 'react'; import { useInView ...

Define variables using specific class components only

Consider a scenario where we define a class as follows: class House { street: string; pools: number; helicopterLandingPlace: boolean; } Now, I have created a service to update my house. putHouse(house: House) { // some put request } How ...

The issue with IE-9 is that it is mistakenly picking up the placeholder value as

My HTML code looks like this: <input id="SLOCriteriaOtherText" name="SLOCriteriaOtherText" style="width: 100%;" type="text" data-role="autocomplete" placeholder="Enter name for 'other' metric..." class="k-input" autocomplete="off" role="textb ...

Implementing Icons in Custom Headers of AG Grid Using vue js

I am working on implementing a new feature in AG Grid where I want to display an info icon in the header along with a tooltip that appears when the icon is hovered over. I have already created a custom tooltip component that works correctly, but once I a ...

Is it possible to replace the catch function in JavaScript with a custom function?

Below is the code snippet: function xyz() { try { var a = someexecutions(); handlesuccess(a) } catch (err) { handleerror(err) } } This type of function is repeated numerous times in my codebase and I am looking for a way to improve it. f ...

When using a Vue.js component, the value of this.$route can sometimes come back

I am attempting to retrieve the parameters from the URL and pass them into a method within a Vue component. Despite following advice to use this.$route, I am consistently getting an 'undefined' response. I have tried various solutions suggested ...

Utilizing Data From External Sources in a React Application

I have encountered an issue with displaying data from another page in a reusable table I created using React. Specifically, I am having trouble getting the value to be shown in <TableCell> Please check out this code sandbox link for reference ACCES ...

How can escape characters be utilized in the JavaScript split function?

Here are two examples that achieve the same result. I'm curious as to why Option 1 was included in a code example I came across instead of Option 2? What is the significance of the forward/backward slashes in '/\&/'? Option 1: ...

why is it that I am not achieving the expected results in certain areas of my work?

I am facing issues with getting an alert response from certain buttons in the code. The AC button, EQUALS button, and the button labeled "11" are not behaving as expected. I have tried troubleshooting but cannot identify the problem. Can someone please ass ...

How can I resolve a MySQL query error in Node.js that is throwing an undefined error?

There seems to be an issue with the second request returning undefined instead of showing the results. The expected behavior is that if the first request returns less than two lines, the second request should be executed. What could be causing this error ...

The Material UI library is signaling that there is an unidentified property called `selectable` being used with the <table> tag

Whenever I try to add the selectable attribute to the Table component in Material-UI using React JS, I encounter an error. Despite checking that selectable is indeed included in TableProps, the issue persists. List of Dependencies : "material-ui": "1.0.0 ...

Determine whether there is only one array in the object that contains values

At the moment, I am attempting to examine an array in order to determine if only one of its elements contains data. Consider this sample array: playersByGender = { mens: [], womens: [], other: [] }; Any combination of these elements may contain dat ...

NuxtJs login feature is functional, but encounters an unauthorized 401 error

I am utilizing the NuxtJs auth module to manage my authorization within the application state. I have created an express API specifically for this purpose, and it functions correctly. Below is the configuration included in my nuxt.config.js file: axios ...

Is it possible to pass a variable from an Axios Response in the Composition API up to the root level?

I need to fetch the headings array from an axios.get call and utilize it at the root level within my Vue component. However, when I attempt to return it, I encounter this error: ReferenceError: headings is not defined Here is the script element in my Vue3 ...