Home > front end >  Execute Spacebar or Backspace with function in Javascript
Execute Spacebar or Backspace with function in Javascript

Time:11-18

this is my code in JavaScript:

document.addEventListener('keypress', event => {
  event.code === 'Space';
})

I want to execute my keyboard with a function of javascript. Thank you for answering me

CodePudding user response:

let element = document.querySelector('input');
element.onkeydown = e => alert(e.key);
element.dispatchEvent(new KeyboardEvent('keydown', {
'key': 'a'
}))

CodePudding user response:

can I use it like this but it's not working. after setting the value that I need then press spacebar or backspace key with a function. it's a date-picker value from input date

    var formatt = function(input) {
        var array = (input || '').toString().split(/\-/g);
        array.push(array.shift());
        return array.join('/') || null;
    };
    await sleep(1000);
    var date_value = document.querySelector('.input-text-date').value;
    var format = formatt(date_value);
    let element = document.querySelector('.input-element > .tp-yt-paper-input');
    element.value = format;
    // element.onkeydown = e => alert(e.key);
    await sleep(2000);
    element.dispatchEvent(new KeyboardEvent('keydown', {
    'key': 'spacebar'
    }))
  • Related