erfan sahab
erfan sahab

Reputation: 25

Is there anyway to use toggle() of jquery dynamically?

Edited:

I want to make a div that it has some divs inside of it. and I want to toggle that divs and when I click on one of buttons I want to disappear not matched divs and appear matched div .This is my code:

<div class="TheToggle">
    <button id="Toggle1">Toggle 1</button>
    <button id="Toggle2">Toggle 2</button>
    <button id="Toggle2">Toggle 3</button>


    <div class="Toggle1">This 1</div>
    <div class="Toggle2">This 2</div>
    <div class="Toggle3">This 3</div>
</div>

Actually at the first I want to display Toggle1 content and when I click on another buttons I wanna appear the div of that button and disappear another one.

Upvotes: 1

Views: 36

Answers (1)

Leonid
Leonid

Reputation: 804

let buttons = document.querySelectorAll('.TheToggle button');

buttons.forEach(b => {
	b.addEventListener('click', () => {
        document.querySelectorAll('.TheToggle > div')
         .forEach(d => d.style.display = 'none');
  	document.querySelector(`[data-hide="${b.getAttribute('id')}"]`).style.display = 'block';
  })	
});
<div class="TheToggle">
    <button id="Toggle1">Toggle 1</button>
    <button id="Toggle2">Toggle 2</button>
    <button id="Toggle3">Toggle 3</button>


    <div data-hide="Toggle1">This 1</div>
    <div data-hide="Toggle2">This 2</div>
    <div data-hide="Toggle3">This 3</div>
</div>

Upvotes: 2

Related Questions