☑ HTML button with touch event – any help?

Hi all

I have a HTML Button (div) and i want to create a touch event on it.
At the moment the tap/click works only if I click on the screen NOT the button.
It’s clearly because of this.app.touch.on(“touchstart”, this.onTouchDown, this);

How can I change this, so “TouchDown” starts when i only press the HTML Button?
Any ideas?

The code from this project did not work for me https://playcanvas.com/project/354600/overview/htmlcss--live-updates
And I can’t get the div with: var button = this.element.querySelector(’#ButtonUp’);

THX

Button.prototype.initialize = function() {
// create DIV element
var div = document.createElement(“div”);
this.element = div;
div.id = “ButtonUp”;
div.innerHTML = this.html.resource;
document.body.appendChild(div);

style = pc.createStyle(this.css.resource);
document.head.appendChild(style);

this.app.touch.on("touchstart", this.onTouchDown, this);   

};

Button.prototype.onTouchDown = function() {
console.log(“clicked”);
// Do STUFF
};

Hi, MadOrb.
I think if you use HTML Button, you’d better using JavaScript’s event instead of PlayCanvas. Something like that
element.addEventListener('click', function(){ //do stuff }, false);

There’s another way, 2D Image.

Hope that helps

1 Like

Thanks for your input @WingUNO :thumbsup:

It’s simpler with the eventListener and the click function.
Wrong search the whole time :sweat_smile: but now i found this and after some changes it works well for me

https://playcanvas.com/editor/scene/331584
http://playcanvas.com/editor/scene/331584/launch

:point_up: it’s old code… and for everyone that needs this, here is the original code updated:

var Buttons = pc.createScript(‘buttons’);

Buttons.prototype.initialize = function() {
var self = this;

this.createButton("Button1", 20, 20, function (e) {
    self.entity.primitive.color = new pc.Color(1,0,0);
});
this.createButton("Button2", 20, 60, function (e) {
    self.entity.primitive.color = new pc.Color(0,0,1);
});

};

Buttons.prototype.createButton = function(name, x, y, onClick) {
var button = document.createElement(“button”);
button.textContent = name;

button.style.position = "absolute";
button.style.left = x + "px";
button.style.top = y + "px";
button.style.width = "110px";
button.style.height = "50px";
button.style.backgroundColor = "#333";
button.style.color = "#fff";
button.addEventListener("click", onClick, true);
document.body.appendChild(button);    

};

// Called every frame, dt is time in seconds since last update
Buttons.prototype.update = function(dt) {
};