Keypress-triggered function for reading lines in Word - Word Addin

I am currently working on developing an addin for Microsoft Word that can read the entire line of text in a Word document and compare it to a dictionary on each keypress event. The goal is to capture the text input by the user, save it to a variable, and still allow the keypress to function as usual within Word. How can I create a function that triggers every time a key is pressed?

Since this is my first time coding a Word addin using Javascript, there may be something obvious that I have overlooked. Please provide guidance as if I am a beginner in this area.

To start, I used this initial file as a reference: https://learn.microsoft.com/en-us/office/dev/add-ins/quickstarts/word-quickstart?tabs=visualstudio

Although I attempted to incorporate the following code snippets into my project, they did not yield any results:

var doc = Office.context.document;
doc.addHandlerAsync(Office.EventType.DocumentSelectionChanged, function () {
    insertEmersonQuoteAtSelection;
    console.log('Ran new function.')
});

In addition to the above code, I also included the following lines along with its associated context, but again, no changes were observed:

(function () {
    Office.onReady(function () {
        // Office is ready.
        $(document).ready(function () {
            // The document is ready.
            // Use this to check whether the API is supported in the Word client.
            if (Office.context.requirements.isSetSupported('WordApi', '1.1')) {
                // Implement functionality specific to the newer APIs.

                addEventListener('keydown', insertEmersonQuoteAtSelection);
                $(document).keypress(insertEmersonQuoteAtSelection);

                $('#emerson').click(insertEmersonQuoteAtSelection);
                $('#checkhov').click(insertChekhovQuoteAtTheBeginning);
                $('#proverb').click(insertChineseProverbAtTheEnd);
                $('#supportedVersion').html('This code is using Word 2016 or later.');
            }
            else {
                // Informing you that this code will not be compatible with your Word version.
                $('#supportedVersion').html('This code requires Word 2016 or later.');
            }
        });

        $(document).ready(function () {
            $(document).keypress(function (e) {
                if (e.keyCode == 39) {
                    insertEmersonQuoteAtSelection;
                }
            });
        });
    });

I proceeded to test a specific key (e.g. 39) by adding another $(document).ready(function () { block, yet unfortunately, it did not respond as intended.

My objective was simply to confirm if executing a known working function like insertEmersonQuoteAtSelection upon a keypress would trigger successfully, but no execution took place.

Answer №1

If you want to implement event handling, consider using addEventListener in the code snippet below:

window.addEventListener('keydown', insertEmersonQuoteAtSelection);

I personally tested this method and it worked successfully for me. If you are facing issues, please ensure that you are placing the code snippet correctly. It's possible that you might be making a mistake, so double-check or provide more details.

For creating an add-in, it is advisable to utilize the Yeoman generator as the preferred method. I recommend giving it a try. https://learn.microsoft.com/en-us/office/dev/add-ins/quickstarts/word-quickstart?tabs=yeomangenerator

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

Steps for replacing the firestore document ID with user UID in a document:

I've been attempting to retrieve the user UID instead of using the automatically generated document ID in Firebase/Firestore, but I'm encountering this error: TypeError: firebase.auth(...).currentUser is null This is the content of my index.js ...

Modifying HTML video player style using jQuery

I am currently working on hiding the gradient and timeline components of an HTML video player using jQuery or JavaScript. Although I have successfully achieved this using CSS: video::-webkit-media-controls-panel { background-image: none !important; ...

Changing the Div heights in Material UI with grid layout customization

I have a project that requires me to implement material-ui. Is there a way I can adjust the width and height of the div containing the "Sign In With" text (as shown in the first image) to bring the buttons closer to the text? Transformation from this: ht ...

Next.js encountered an invalid src prop

Error: The src prop is invalid () on next/image, the hostname "scontent-atl3-2.xx.fbcd.net" has not been configured under images in your next.config.js For more information, visit: https://nextjs.org/docs/messages/next-image-unconfigured-host ...

What is the best way to activate an onchange function when using a <select> element?

Is there a way to automatically trigger a JavaScript function without the need for user input, while still having a default option selected? <select class="custom-select" name="" id="timer1numbers" onchange="getSelecte ...

What is the best way to steer a vehicle in the desired direction by utilizing the arrow keys on the keyboard?

Image1 Image2 While using visual studio code, I noticed that I can move a car forwards and backwards with the arrow keys on the keyboard. However, it doesn't seem to turn when I try to move in opposite directions. Is there a way to achieve this thro ...

Tips for triggering a postback with jquery autocomplete when an option is selected

TEST AREA I've put together a basic demo of jquery-ui autocomplete. QUERY How do I trigger a postback when a selection is made from the autocomplete list? HTML <select id="ddl"></select> <input id="field" type="text"></input& ...

Is it possible to conditionally call the Apollo Client in my Vue template script?

I have a scenario where I pass a query to the apollo client in my template file using a script tag. However, I want to find a more efficient way to handle this without having to specify the query every time. My idea is to pass a boolean value through a pro ...

"Enhancing User Experience with Bootstrap's Smooth Transition Effects for fadeIn() and fade

As someone who is new to html and JavaScript, I have the following html code: <div class="row" > <button class="..." id="button"> ... </button> <div class="..." id="box"> ... </div> </di ...

The issue arises when the cache code in jQuery Ajax interferes with the callback function, causing it to

I encountered an issue with my code related to cache. The problem arises when there is an ajax call with a callback in the success function. var localCache = { /** * timeout for cache in millis * @type {number} */ timeout: 30000, ...

The issue arises when attempting to use input alongside debounce, event.persist(), and storing the value at the parent component

Is there a way to implement an input field with debounced search where the value is passed from the parent component? Currently, when I pass the value from the parent component it doesn't work as expected. What would be the correct approach to make th ...

Struggling with setting properties in React and getting the error message "Cannot set properties of null (setting 'inner HTML')"?

import React, { useState } from "react"; export default function DropDown() { const handleClick = () => { document.getElementById('id').innerHTML='Hello world' } return ( <> <button onClick={handleClic ...

Step-by-step guide on programmatically closing the Material-UI DropDownMenu

http://www.material-ui.com/#/components/dropdown-menu Having encountered a styling issue, I was compelled to rearrange the order of components within my material-ui DropdownMenu. Nevertheless, some buttons (renderNavLink) are now failing to close the Dro ...

Encountering difficulties in retrieving the JSON data from the web service

My external web service contains JSON data which has been validated using the JSON Validator website. However, I am facing an issue where the success function in the code below is not running at all. The web service necessitates that the email and password ...

Retrieve the value of a cell in Google Sheets

Seeking assistance on how to retrieve the content of a cell in Google Sheets and store it for comparison purposes at a later time. My search efforts have led me to various online resources such as the Visualization API and the Sheets Script, but I have n ...

Adding text to several elements by class in Vue.js

Although I am aware that directly modifying the dom in vue.js is not recommended, I find that the alternatives would result in much messier and harder to maintain code. The Challenge Currently, with the use of vue-i18n, I need to dynamically move the curr ...

Is there a way to alter the color of a button once it has been clicked?

For a school project, I am working on coding a website to earn extra credit. My goal is to create a fancy design that stands out. One of the main things I am trying to achieve is having a button change color when it is clicked, similar to how it highlight ...

The functionality of the Toastr "options" seems to be malfunctioning

I am having some trouble with my Toastr notification messages. While the message does display, I seem to be unable to make use of any options that I set. Despite specifying some options, they do not seem to work as intended. $('#editButton').c ...

Tips for incorporating WinBox JS into Angular applications

I've been experimenting with the WinBoxJS JavaScript library, and I'm familiar with using it in plain JS. However, I'm now attempting to integrate it into my Angular project. Can anyone guide me on how to achieve this? https://www.npmjs.com/ ...

Alternative form for non-javascript browsers in the absence of script

I'm currently working on a landing page for an upcoming product, and I've run into a bit of a snag. <form novalidate method="POST" class="subscribe-form"> <noscript> </form> <form method="POST" action="/ ...