How can I connect my button to enter key?

I had linked button to another page. I want to connect that button with enter key in keyboard. If someone press enter he will be redirected to next page. I don’t know much about coding as I am a beginner. Anyone please help…

The button work with Enter key click by default. For that you have to focus on button with Tab navigation.

  • You click key Tab .

  • You can see where you focus with blue outline.

  • Click Enter key (the same as click with mouse or Space key)

https://www.wix.com/velo/reference/$w/button/onclick

I tried this. But this is not working.
Please check the first page concept. It will make you understand better
madaansaksham2809.wixsite.com/site

Hi Shaksam,

I understand that you want a user to click a button by using the enter key.

I would approach this by making a text input element, and focusing on it, when the page loads.

$w('#TEXT_INPUT_ID').focus()

Then create an onKeyPress event handler for the text input, and put this inside it

if (event.key === "Enter") {
page()
}

Make a new function called page, which directs the user to the page you want them to go to

function page() {
    wixLocation..to("/home-1")
}

Remember to import wixLocation at the top of the page!

Happy coding!

Unfortunately buttons in Velo doesn’t have focus method.
https://www.wix.com/velo/reference/$w/button

@alexanderz61239 I said focus on the text input, not the button…

1 Like

@madaansaksham2809
I see. You want to create a global handler for the Enter key.

Yes, I agree with @alexobc . You can use some hack with text input. For example, create a “focus trap”.

Demo: https://alexanderz5.wixsite.com/focus-trap

Code:

import wixLocation from 'wix-location';
 
// Navigation
const nextPage = () => {
  wixLocation.to('/next-page');
};
 
$w.onReady(function () {
  const button = $w('#button1');
  const focusTrap = $w('#input1');
 
  button.onClick(() => {
    nextPage();
  });
 
  focusTrap.onKeyPress((event) => {
   if (event.key === 'Enter') {
     nextPage();
   }
  });

  // Focus trap. 
  // If user click somewhere then we return the focus to input
  focusTrap.onBlur(() => {
   setTimeout(() => {
     focusTrap.focus();
   }, 100);
  });

  focusTrap.focus();
});

@alexanderz61239 Nice one! I completely forgot about the focus trap!

Please elaborate more, I don’t know anything about coding. I am new for this. I tried your code it responded by pressing enter but didn’t worked to load next page

@madaansaksham2809

Sorry, if you don’t know JavaScript then I couldn’t help you. The first you should learn the JavaScript then you can work with Velo.

https://javascript.info/

Your code worked! But it is working only on preview not on published site. Please help. @Alexander Zaytsev Please help!!