Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

div into a js button [duplicate]

I have a <div> that I have formatted very carefully to look nice, and I need to make it have the functionality of a button. How would I go about doing this?

like image 384
skiller185 Avatar asked Aug 24 '26 09:08

skiller185


2 Answers

You can give that div tag a onclick function as follows.

function myfns() {
    console.log("Clicked")
}
<div id="btn" onclick="myfns()">Click</div>
like image 63
Nisal Edu Avatar answered Aug 25 '26 23:08

Nisal Edu


First recommendation is to use a <button> instead. You can style that however you want as well. If that is not an option for some reason, you'll have to do a few different things to create a proper button out of a div element (to ensure that it works with keyboard and screen readers).

  • Add click handler. Eg btn.addEventListener('click', clickHandler);
  • Add enter key handler. Eg btn.addEventListener('keyup', keyHandler);
  • Add button role. role="button"
  • Add it to tab order: tabindex="0"

var buttons = document.querySelectorAll('.btn');

buttons.forEach(function (btn) {
  btn.addEventListener('click', function(e) {
    console.log('clicked');
  });
  
  btn.addEventListener('keyup', function(e) {
    if (e.key === 'Enter') {
      console.log('keyup');
    }
  });
});
.btn {
  display: inline-block;
  background: #eee;
  border: 1px solid #aaa;
  padding: 6px;
  cursor: pointer;
}
<div class="btn" role="button" tabindex="0">My Button</div>

<div class="btn" role="button" tabindex="0">My Button</div>

<div class="btn" role="button" tabindex="0">My Button</div>
like image 30
amcdrmtt Avatar answered Aug 25 '26 23:08

amcdrmtt