Problem with Click Button on mobile JavaScript

Hello

I am a french beginner in javascript and I am working on a game project on Hype. For the moment I put all my actions of buttons on a single JavaScript that I load to loading of my scene.

Here is a sample code I use

var myButton1 = hypeDocument.getElementById(‘name-bt1’);

myButton1.onclick = function () {
//actions of the button
}

myButton1.ontouchstart = function () {
//actions of the button for mobile
}

My big problem is that for each of my buttons, I am forced to put two functions so that it works on mobile and tablet.
Is there not a code that allows to combine the two actions in a single function.

Thanks in advance for helping me optimize my project

No one has solutions to my problem ?

A little bit of patience :wink: We are many people mostly with day jobs :smiley:

Hype has a built in action that covers both click (tap) and mousedown (touchstart). If you are using Hype then choose your button element on stage and then go to the "Actions" inspector and choose the plus sign next to the appropriate action.

Here you can see a couple of actions being applied to the element. One is "Run Javascript". Here it will create a function that you can use to type in your relevant Javascript code that you need to run on those actions.

#####Note, Click and Touchstart are 2 different events, if you need to have similar reactions they might act differently.

If you still want to go the Javascript route as in your post then you can create a variable that checks to see if the machine has touchstart and use that instead of click. If it doesn't then use click.

clickEvent = (function() {
  if ('ontouchstart' in document.documentElement === true)
    return 'touchstart';
  else
    return 'click';
})();

This code needs to run before it is called.

2 Likes

Thank you for the answer. Indeed I know that Hype handles both directly but when you have a lot of buttons, it does too many functions to create. I prefer to store everything in a single javascript when loading my scene. I find it much easier to manage.

I will test to change my code to see if I can optimize it all

DId you not see the last bit of code in my post. That will give you either “toushstart” or “click” depending on the device. So, to make it more clear:

var clickEvent = (function() {
  if ('ontouchstart' in document.documentElement === true)
    return 'touchstart';
  else
    return 'click';
})();

var myButton1 = hypeDocument.getElementById('name-bt1');
myButton1.addEventListener(clickEvent, function(e){
    e.stopPropagation();
    // do something on click or touchstart
})

You can also use just one function for all your buttons perhaps and just run a conditional to see which button is firing the function and run code specific to that.

3 Likes

Thank you very much, it works. It is the best.