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

How do I return a <div> element to its initial state after JavaScript has made changes to it?

So, I have this situation where a DIV contains a form. After users submit the form successfully, I want to replace the form with a simple message saying "everything is good now". This is how I currently do it: $("#some_div").html("Yeah all good mate!"); ...

jQuery: Eliminating Parent Elements

Currently, I am developing a small web application that allows users to create lists which are then formatted and emailed to them. However, I am facing difficulties in implementing a method that will allow users to delete list items without clearing the en ...

Is it better to use Asynchronous or Synchronous request with XMLHttpRequest in the Firefox Extension for handling multiple requests

As a newcomer to developing Firefox Add-Ons, my initial project involves calling an external API in two steps: Step 1) Retrieve data from the API. Step 2) Use the data retrieved in Step 1 to make another call to the same API for additional information. ...

Utilize regular expressions to substitute content with HTML tags within a directive

While working with Angular JS to iterate through Twitter tweets using ng-repeat, I encountered the need to highlight certain parts of the tweet string such as @tag and #hash. To achieve this, it was suggested to utilize replace method to wrap these element ...

Creating a flash message following a redirect in AngularJS

Just diving into Angular JS and need some clarification. How can I set a flash message after a redirect? Here's my scenario: I have a form where I save data using an HTTP request. Upon success, I navigate to another page using window.location(). Now, ...

Angular 8 experiencing unexpected collision issues

Currently, I am utilizing Angular 8 with "typescript": "~3.5.3". My objective is to handle the undefined collision in my code. const { testLocation } = this.ngr.getState(); this.step2 = testLocation && testLocation.step2 ? testLocat ...

Datagrid in AngularJS does not update filters upon refresh

Currently, I am attempting to implement name filtering with Angular JS using the following library: https://github.com/angular-data-grid/angular-data-grid.github.io. However, an issue arises when searching as the results do not refresh immediately; only up ...

Can a 1D array be utilized to create a 2D grid in React?

I needed to display a one-dimensional array in a 2D grid format with 3 rows and 3 columns. The array itself contains numbers from 1 to 9. const array = Array.from({ length: 9 }, (_, i) => i + 1); In my React component, I have it rendering as a series o ...

Tips for effectively eliminating errors in a redux store

Within my react-redux application, I have implemented a system to catch error responses from redux-saga. These errors are saved in the redux-store and rendered in the component. However, a major challenge arises when trying to remove these errors upon comp ...

Is it permissible for me to incorporate a package from the dependencies listed in the package-lock.json file into my

I'm looking to incorporate date-fns into my project. I currently have react-datepicker, which also uses date-fns. Can I simply utilize date-fns from react-datepicker, or do I need to install it separately in my project? ...

I encountered an issue with adding a console log in the getStaticProps() function that resulted in the error: SyntaxError: Invalid Unicode escape sequence at eval (<anonymous>

Welcome to my users.js page! import React from 'react' const displayUsers = ({users}) => { return ( <> { users.map(user => { return <div key={user.id}> {user.name} </div> }) } </&g ...

Discover the "route" of a JSON element using JavaScript

I've been struggling to retrieve the "path" of a specific AngularJS scope variable. My end goal is to utilize this "path" as the ng-model for dynamically generated forms. Below is my current code: my_code.js: var my_data = { name: "fred", numbe ...

Using jQuery to make an Ajax post request that will load the current page with additional form data appended to the

Below is the HTML code for my registration form: <form id="registerForm"> <input type="text" pattern="[A-Za-z]{1,20}" placeholder="First Name" name="guestFName" title="Up to 20 alphabetical characters" required> <inp ...

How can one effectively overcome the constraint in HTML5 canvas that prevents altering the positions of previously sketched elements?

I am currently working on creating a wind map that displays data from seven different weather stations. My goal is to develop a fluid and interactive map similar to the ones found in this animation or this animation. In my research, I came across an artic ...

Creating a group object based on ID using react-native and JavaScript - a step-by-step guide

I have an array of objects that I need to reorganize so that each object with the same guid is grouped together. For instance, given this array; [ {"guid":"3a03a0a3-ddad-4607-9464-9d139d9989bf","comment":"text&quo ...

Effective methods to avoid showcasing AdSense advertisements

For the purpose of creating a responsive design, I am attempting to hide an adsense ad unit on smaller screen sizes. Although I am familiar with the method of using css media queries as outlined on Google AdSense support page, I have encountered an error w ...

Saving an item using localStorage

I've been struggling to figure out how to make localStorage save the clicks variable even after refreshing the browser. Initially, I attempted using JSON.stringify and JSON.parse but later discovered that using parseInt could be a more suitable optio ...

Displaying success and failure messages on a modal window using Ajax in PHP form

Unable to display error messages or success messages in the same modal window. I have set up Wordpress and using the following code: Form <form id="formcotizador" method="post" action="<?php echo get_template_directory_uri(); ?>/cotizador/procc ...

The file-loader in Webpack is failing to copy the files and update the URL

I am encountering an issue with webpack file loader where it is not outputting image files. This problem arises while also importing HTML files as partials in my Angular app. Below is my webpack configuration for handling images using the file-loader: [w ...

Vue.js does not display HTML properly within the vue-swal component

I'm currently working on integrating HTML content into a Sweet Alert popup using this code snippet Link: https://www.npmjs.com/package/vue-swal this.$swal({ title: '<i>Custom HTML</i>', html:`This is an <em> em ...