Blocking the space bar in JavaScript is a useful technique that can be

I'm in the process of developing an application and I'm looking to prevent the space bar from scrolling my page

My framework of choice is VUE, and I am trying to trigger a method using an event handler

However, when I attempt to call the 'keymonitor' method, I encounter an error:

An unexpected block statement surrounds the arrow body; please move the returned value immediately after the =>

Is there a proper way to invoke the 'keymonitor' method?

window.addEventListener('keydown', e => {
  return this.keymonitor(e)
})


keymonitor(event) {
  if (this.sendkey === 1) {
    if (event.key.length === 1) {
      this.keyDown = {
        cmd: 'keyboard',
        key: event.key,
      }
    } else if (
      event.key === 'Enter' ||
      event.key === 'Tab' ||
      event.key === 'PageUp' ||
      event.key === 'PageDown' ||
      event.key === 'End' ||
      event.key === 'Home' ||
      event.key === 'ArrowLeft' ||
      event.key === 'ArrowUp' ||
      event.key === 'ArrowRight' ||
      event.key === 'ArrowDown' ||
      event.key === 'Backspace' ||
      event.key === 'Delete' ||
      event.key === 'Escape'
    ) {
      this.keyDown = {
        cmd: 'keyboardSpecial',
        key: event.key,
      }
      // event.preventDefault();
    }
    console.log('eventkey: ')
    console.log(this.keyDown)
    this.sendMessage(this.keyDown)
  }
  if (event.which === 32) {
    console.log('SPACE')
  }
  return false
},

Answer №1

Consider using the code snippet below instead of the previous one, as I am not entirely satisfied with the usage of this in the current code:

const keylogger = event => {
  if (this.loggingEnabled === true) {
    if (event.key.length === 1) {
      this.recordedKey = {
        action: 'input',
        keyPressed: event.key,
      }
    } else if (
      event.key === 'Enter' ||
      event.key === 'Tab' ||
      event.key === 'PageUp' ||
      event.key === 'PageDown' ||
      event.key === 'End' ||
      event.key === 'Home' ||
      event.key === 'ArrowLeft' ||
      event.key === 'ArrowUp' ||
      event.key === 'ArrowRight' ||
      event.key === 'ArrowDown' ||
      event.key === 'Backspace' ||
      event.key === 'Delete' ||
      event.key === 'Escape'
    ) {
      this.recordedKey = {
        action: 'specialInput',
        keyPressed: event.key,
      }
      // event.preventDefault();
    }
    console.log('Logged keystroke: ')
    console.log(this.recordedKey)
    this.sendLog(this.recordedKey)
  }
  if (event.which === 32) {
    console.log('SPACE')
    event.preventDefault()
  }
  return false
}

window.addEventListener('keydown', keylogger)

Answer №2

document.addEventListener("keypress", keyWatch);

The keyWatch function will receive the event object as a parameter if specified in its definition.

Remember to place the document.addEventListener below the keyWatch function declaration to avoid any scope issues.

If you want to prevent a specific key (e.g., spacebar) from functioning:

if (event.key === " ") {
    console.log('SPACE pressed')
    event.preventDefault();
  }

return false;

Answer №3

I put together a simplified example based on the concept discussed in this Stack Overflow thread.

const app = new Vue({
  el: '#app',
  created() {
    window.addEventListener('keydown', e => {
      if (e.keyCode == 32 && e.target == document.body) {
        alert('Space bar prevented from scrolling the page');
        e.preventDefault();
      }
    })
  }
});
body {
  height: 100000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input />
  <textarea></textarea>
</div>

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

Issue with React submit button for posting data is not functioning as intended

My dilemma lies within a Modal component containing a Form and Button. The goal is to trigger a POST request (managed in a separate file) upon the user clicking the button, which will run a simulation using the validated input values. Surprisingly, the onC ...

How can HTML and CSS be linked to display images independently?

Check out this code: body{ background-image:url('http://wallpoper.com/images/00/31/33/51/black-background_00313351.jpg'); } div.header{ background-color:#F0F8FF; text-align:center; padding:3px; ...

When the form is submitted, I am unable to record the checkbox value

Hi, I have a question regarding submitting a form to the "/delete" route when a checkbox is checked. Although I am able to submit the form successfully, I am facing an issue retrieving the checkbox value that I assigned using ejs. Below are the relevant co ...

Pressing the "Enter" key in a .Net WinForm Browser Control

How can I simulate the Enter key press event on a web page using the GeckoFX Web Control? I am unable to use SendKeys.Send({ENTER}) Is there a method to trigger the Enter key using JavaScript within a webpage? ...

Code Wizard

I am currently working on a project to develop an HTML editor. How it Needs to Function Elements Inside: Text Area - Used for typing HTML as text Iframe - Displays the typed HTML as real [renders string HTML to UI] Various Buttons Functionality: When ...

Uploading a file using AngularJs

When it comes to uploading an image or file using HTML tag in AngularJS, it seems that the tag is not supported. The solution? Create a custom directive. In my index.html page, I included the following code: <body ng-controller="myController"> ...

Combining an Image with a CanvasJS Graph and Generating a Downloadable Image of the Composite

I am attempting to combine an image (a background image for my graph) with my canvasJS chart. Once these elements have been merged on a canvas, I aim to obtain a DataURL of this canvas, enabling me to download an image of it (depicting the graph along wit ...

Is the UUID key displayed as an object within a Reactjs prop?

Hey there internet pals, I've stumbled upon a mysterious corridor, so dark that I can't see where I'm going.. could really use someone's flashlight to light the way. I have put together a basic, no-frills to-do list program. It consi ...

Steps for handling errors in Node.js when the query result rowCount is 0 and throwing an error in response

If the rowcount is 0, I need to send a response as failed. If the rowcount is 1, I need to send a success status. Can someone please assist me with this? When I try to print (client.query), it displays the result in JSON format (refer to attached image). ...

The v-for loop is looking for a numerical value, but it received something that is Not

The v-for directive is having trouble accessing the nStars prop in order to run a loop. I am attempting to display multiple stars by using the component <display-stars>. However, the component does not seem to be receiving the nStars prop for the loo ...

Utilizing a mutual RxJS subject for seamless two-way data binding in Angular 2

I have a unique service dedicated to managing app configurations class Configuration { get setting() { return dataStore.fetchSetting(); } set setting(value) { dataStore.saveSetting(value); } } This configuration is linked to components t ...

JavaScript Tutorial: Simplifying Character Ranges for Conversion

I am currently working on adapting code I found here to create a virtual keyboard for a foreign alphabet using an online textarea. Below is the modified code: <textarea id="txt"></textarea> <script src="https://ajax.googleapi ...

How to effectively leverage useMediaQuery in material ui?

Upon completing the web application, I have made the decision to ensure it is mobile-friendly. Utilizing the material UI framework with react, I delved into the documentation but found myself uncertain about how to effectively implement it. Let me provide ...

Invoking a PHP function within a JavaScript file

I'm facing an issue with calling a PHP function from JavaScript. I have written a code snippet where the PHP function should print the arguments it receives, but for some reason, I am not getting any output when running this code on Google Chrome. Can ...

How can I adhere to Angular 2's naming convention for Input and Output as suggested by the styleguide?

Working with inputs and outputs while following Angular 2's styleguide naming convention Initially, my directive was defined like this: ... inputs: [ 'onOutside' ] ... export class ClickOutsideDirective { @Output() onOutside: EventEmitter ...

The Socket.io Chat application is indicating a memory leak with the EventEmitter, detecting 11 listeners that have been added. To resolve this issue

My private chat application is built using socket.io, node.js, and MySQL. However, I encountered an error when trying to use socket.on('example', function(data){...});. The error code thrown is related to a possible EventEmitter memory leak with ...

Tips on recycling JavaScript files for a node.js API

I'm currently using a collection of JS files for a node.js server-side API. Here are the files: CommonHandler.js Lib1.js Lib2.js Lib3.js Now, I want to reuse these JS files within an ASP.NET application. What's the best way to bundle these f ...

React cannot be utilized directly within HTML code

I am looking to incorporate React directly into my HTML without the need for setting up a dedicated React environment. While I can see the test suite in the browser, my React app fails to load. Below is the content of my script.js file: I have commented ...

Incorporating a new method into the Object prototype to provide universal access across all modules

I've been delving into Typescript experimentation and I'm attempting to enhance the Object prototype by adding a property that can be accessed by all objects within my modules. Here's what I've developed so far: In a Common.ts file O ...

What's the best way to add line numbers to source code on an HTML webpage after parsing?

I am currently working with AngularJS and MongoDB. In my MongoDB data, there are some text elements that contain a \n, causing each line to be displayed on a new line based on the occurrence of \n. However, I also want to add line numbers to each ...