Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a transparent button with JavaScript?

I want to create a transparent button so that the user can still see the image underneath the button but they can click on the button as well.

So I tried making a button like this:

var howToPlayDiv = document.createElement('input');
howToPlayDiv.type = "button";
howToPlayDiv.style.height = '48px';
howToPlayDiv.style.width = '412px';
howToPlayDiv.style.background = "rgba(0,0,255,0.5)";
howToPlayDiv.style.position = "absolute";
howToPlayDiv.id = "howToPlayDiv";
howToPlayDiv.onmouseenter = "changeMenu('howToPlayDiv', 'mouseenter')";
howToPlayDiv.onmouseleave = "changeMenu('howToPlayDiv', 'mouseleave')";
howToPlayDiv.onclick = "changeMenu('howToPlayDiv', 'mouseclick')";
document.body.appendChild(howToPlayDiv);

But this doesn't work. I tried many variations of the above code as well - but to no avail. Sometimes, I could click only on the sides of the button (those were not transparent). Sometimes, I could not even do that.

How can I create a transparent, clickable button?

(BTW, I'm extremely new to JavaScript {about a week}.)

EDIT: Aha! I found out that the problem now lies with the fact that the event handlers are not firing - basically, this has nothing to do with the button's opacity. So now: How can I create an event handler for the button?

like image 658
JavaAndCSharp Avatar asked Oct 16 '25 09:10

JavaAndCSharp


1 Answers

I added these, works for me:

howToPlayDiv.style.background = "none";
howToPlayDiv.style.border = "none";

But make it a button (since that's what it is), the benefit of a button is that you can set the background image to whatever you want.

<button type="button" style="background:url('/url/to/image') no-repeat left top; height:48px; width:412px;"></button>

...for example. Of course you can create this element via JavaScript as your are doing.

EDIT:

It wasn't clear to me from your question what wasn't working for you, sorry. Try assigning your callbacks thusly:

howToPlayDiv.onmouseenter = function(){changeMenu('howToPlayDiv', 'mouseenter')};
howToPlayDiv.onmouseleave = function(){changeMenu('howToPlayDiv', 'mouseleave')};
howToPlayDiv.onclick = function(){changeMenu('howToPlayDiv', 'mouseclick')};

Cheers

like image 120
Madbreaks Avatar answered Oct 18 '25 01:10

Madbreaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!