1

I have some jQuery code and I was wondering is there anyway to convert it to javascript. like is there a program or something that will help me out?

See the code i'm trying to convert:

$("body").trigger($.Event("keydown", { keyCode: 32 }));
$("body").trigger($.Event("keyup", { keyCode: 32 }));

i tried to translate / convert using api.jquery.com but i failed i'm new to this.

document.querySelectorAll("body").trigger(new Event("keydown", { keyCode: 32 }));
Lewis Browne
  • 904
  • 7
  • 23
Loperz
  • 13
  • 2
  • 5
    It's already in JavaScript. jQuery isn't a language, it's a library of utility functions. What you're asking is: How do I take this code using jQuery and have it use [the DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) directly? – T.J. Crowder Sep 27 '18 at 12:41
  • At least related: https://stackoverflow.com/questions/42610403/how-to-trigger-a-keypress-event-in-javascript-without-jquery, http://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method – T.J. Crowder Sep 27 '18 at 12:42

1 Answers1

1

I don't know if some kind of translator / converter exists, but for these lines of code you can rewrite them to work directly on the DOM like this:

document.body.onkeydown = function(e){
    if (e.keyCode == "32")
        //do stuff
};

document.body.onkeyup = function(e){
    if (e.keyCode == "32")
        //do stuff
};

As suggested below, you might want to use addEventListener() instead of inline event handlers, here is a good explanation of the differences between these methods. addEventListener vs onclick

Luca Corsini
  • 738
  • 4
  • 20
  • 2
    You should use [`addEventListener()`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) instead of `.onX` attributes. – str Sep 27 '18 at 12:50
  • Yep, you're right. the onX works fine here, but I putted a link that explains the differences between the two methods – Luca Corsini Sep 27 '18 at 12:54