Using Key Press to Rotate Messages - Jquery

Need help with rotating an array based on alphanumeric key presses? Check out the code snippet I've been working on below. Unfortunately, I'm having trouble getting the loop to function properly. Any suggestions or feedback would be greatly appreciated!

Here's the array of rotating messages that I'm using:

var rotatingMessages = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
$(document).ready(function() { 
  $(document).keypress(function(e){
    var code = e.KeyCode || e.which;
    var messages = (code-1) % 10;

    $("div#output").html(rotatingMessages[messages]);
  });
});

Answer №1

If you want to implement a cycling array values feature, you can achieve this by utilizing the shift and push methods.

var rotatingItems = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape', 'kiwi', 'lemon', 'mango', 'orange'];
$(document).ready(function () {
    $(document).keypress(function (e) {
        var item = rotatingItems.shift(); //get the first item from the array
        rotatingItems.push(item); //add it back at the end to cycle through
        $("#results").html(item);
    });
});

Code example on Fiddle

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

"Enhance your PHP-MySQL data tables by implementing the Datatable Server Processing script using ssp.class.php

My goal is to build a data grid using the Datatables jQuery plugin and handle server-side processing with the provided ssp.class.php. While it initially worked, I encountered an issue when trying to retrieve data from multiple tables. To solve this, I util ...

Controller encounters a error when requiring a module

Struggling to set up Stripe for my app, I've encountered some issues with the module implementation. Typically, I would require a module at the top of the file to use it. However, in the paymentCtrl file, when I do this, it doesn't work and I rec ...

What is the reason behind this HTML/CSS/jQuery code functioning exclusively in CodePen?

I have encountered an issue where this code functions properly in JSFiddle, but not when run locally in Chrome or Firefox. I suspect there may be an error in how the CSS or JavaScript files are being linked. In the Firefox console, I am receiving an error ...

What is the reasoning behind CoffeeScript automatically adding a function when extending an Object?

I'm currently working on a helper method to identify the intersection of two hashes/Objects in this manner... Object::intersect = (obj)-> t = {} t[k] = @[k] for k of obj t x = { a: 1, b: 2, c: 3 } w = { a: true, b: 3 } x.intersect(w) #=> ...

Concealing the nearest object

I am currently working on using jquery to hide certain content on a website's index page. Within the fiddle, there is commented out code which I have been experimenting with - however, it hides all content divs if any toggle link is clicked. HTML & ...

Implementing ASP MVC3 - Utilizing partial views to dynamically add new HTML elements to the webpage

Currently, I have implemented an Ajax call in my ASP MVC3 view to add a new list item to the page dynamically. The process involves making an Ajax call from the view to a controller action that returns a partial view. The jQuery script is then set to use t ...

The resource was identified as a document but was sent using the MIME type application/json

I'm having an issue with posting to a jQuery modal's Action and receiving JSON in return. Every time I try, I encounter the following error: Resource interpreted as Document but transferred with MIME type application/json Instead of staying on ...

Can you explain the distinctions among <Div>, <StyledDiv>, and <Box sx={...}> within the MUI framework?

When exploring the MUI documentation, I came across a table of benchmark cases that can be found here. However, the differences between the various cases are not clear to me. Can someone please explain these variances with real examples for the following: ...

Conflict in Vue.js between using the v-html directive and a function

Below is the component template for a notification: <template> <div> <li class="g-line-height-1_2"> <router-link :to="linkFromNotification(item)" @click.native="readNotification(item)" v-html="item. ...

Steps for referencing a custom JavaScript file instead of the default one:

Currently, I am utilizing webpack and typescript in my single page application in combination with the oidc-client npm package. The structure of the oidc-client package that I am working with is as follows: oidc-client.d.ts oidc-client.js oidc-client.rs ...

Updating two separate <DIV> elements with a single AJAX request

Can two different targeted DIVs be updated simultaneously using a single ajax call? Consider the index.html code snippet below: <script> xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.rea ...

Using the jquery-ui-daterangepicker to fetch date values within an MVC controller

I have successfully implemented the jquery-ui-daterangepicker. How can I extract the start and end dates when submitting to my controller? Controller: [HttpPost] public ActionResult EmailReport(DateTime start, DateTime end) { int totalEma ...

Guide to importing firebase-functions and firebase-admin using ES6 syntax for transpilation with Babel in Node 10

I've been working on my cloud functions in ES6 and using Babel to transpile them for the Node v10 environment. But, I've come across an odd issue. It seems that when I import firebase-functions like this: import functions from 'firebase-fu ...

JavaScript animation is not functioning as expected

I created a div with the id of "cen" and gave it a height and width of 50px. $(document).ready(function() { $("#cen").animate({ height: 500px, width: "500px", }, 5000, function() { // Animation complete. }); }); Unfort ...

Unable to trigger AJAX POST with jQuery click handler

Important Note: Personally, I have a preference for utilizing jQuery over the shorthand $; although it involves more typing, I find it to be more readable. I am working on a simple form that allows users to input their first and last names as well as an e ...

How to retrieve the filename from a URL using Node.js

In my Node.js script, I have the following type of link: 148414929_307508464041827_8013797938118488137_n.mp4.m4a?_nc_ht=scontent-mxp1-1.cdninstagram.com&_nc_ohc=_--i1eVUUXoAX9lJQ-u&ccb=7-4&oe=60835C8D&oh=61973532a48cb4fb62ac6711e7eba82f& ...

eliminate empty lines from csv files during the uploading process in Angular

I have implemented a csv-reader directive that allows users to upload a CSV file. However, I have noticed an issue when uploading a file with spaces between words, resulting in blank lines being displayed. Here is an example: var reader = new FileReader ...

Revolving mechanism within React.js

I am currently developing a lottery application using React.js that features a spinning wheel in SVG format. Users can spin the wheel and it smoothly stops at a random position generated by my application. https://i.stack.imgur.com/I7oFb.png To use the w ...

Tips for implementing a boundary on a multipart/form-data request when utilizing the jquery ajax FormData() function for handling several files

I'm facing an issue with my HTML form that needs to upload 3 parts to an existing REST API in a single request. The problem lies in setting a boundary on a FormData submission and I haven't been able to find relevant documentation for it. I&apos ...

Facing continuous 404 errors while working with nodejs and express

While attempting to collect data from a local host webpage's registration form that captures user information, I encounter an issue upon pressing the submit button A 404 Error is displayed stating "page not found", preventing the collection and out ...