No button click event in tabs (Tampermonkey)

49 views Asked by At

I have made single tabs that contain buttons. enter image description here

  // Create the tab content
  const tabContent = document.createElement('div');

  // Add your desired content for each tab dynamically
  const tabContents = [
        '<button class="CodeButton" onclick="myFunction">Button1</button><br/><button class="CodeButton">Button2</button>'
  ];


function myFunction() 
{  
alert("test"); 
}

My goal is that after the button press something happens, e.g. a notification comes or the size of the elements of the page changes.

Unfortunately I can't get it to work , to make the "click event". I guess it has to do with the fact that the tabs are "container".

1

There are 1 answers

0
Ludolfyn On

It's because you need to call the function with the parentheses:

onclick="myFunction()"   // Calling the function with parentheses "()"

It's not always necessary, but in this case it is. Run the example below to test it:

const tabContents = [
  '<button class="CodeButton" onclick="myFunction()">Button1</button>', 
  '<button class="CodeButton">Button2</button>'
]

function myFunction() {  
  alert("test")
}

function selectTab(event) {
  const tab = event.currentTarget
  const selectedTab = document.querySelector('.tab.active')
  selectedTab.classList.remove('active')
  tab.classList.add('active')
}

function addTabContent(tab) {
  const tab1ContentWrap = document.querySelector(tab + ' .tab-content')
  tab1ContentWrap.innerHTML = ''
  tabContents.forEach(content => {
    tab1ContentWrap.insertAdjacentHTML('beforeend', content) 
  })
}

addTabContent('.tab-1')
.tab-group {
  display: inline-flex;
  gap: 3px;
  position: relative;
  
  .tab {
    .tab-name {
      padding: 10px;
      background-color: #ccc;
      text-align: center;
      cursor: pointer;
    }
    .tab-content {
      padding: 10px;
      display: none;
      position: absolute;
      left: 0;
    }
  }
  
  .tab.active {
    .tab-name {
      border: 2px solid #555;
    }
    .tab-content {
      display: block;
    }
  }
}
<div class="tab-group">
  <div class="tab tab-1 active" onclick="selectTab(event)">
    <div class="tab-name">Tab 1</div>
    <div class="tab-content">Place content 1 here</div>
  </div>

  <div class="tab tab-2" onclick="selectTab(event)">
    <div class="tab-name">Tab 2</div>
    <div class="tab-content">Place content 2 here</div>
  </div>
</div>