Using this. to prevent duplication of toggle code


i have the very first toggle code below, its very simple, but I may need up to 15 of these, so rather than duplicating the script to cover each new button and div, is there a way to use just one click function with maybe .this


    <button>Invoicing Office</button>

    <div id="invoicing">This is a paragraph.</div>

I forgot to add that when the page loads all the div’s need to be open, so the first toggle is too close each one up as necessary.

Hi @multichild, you might specify the ID (or any selector) of the element to toggle as a data attribute on the corresponding buttons:

<button data-toggle="#invoicing">Invoicing Office</button>
<button data-toggle="#contact">Contact info</button>

<div id="invoicing">Lorizzle shiznit cool bizzle amizzle</div>
<div id="contact">Consectetuer adipiscing elit</div>
$('[data-toggle]').click(function () {
  // Here, this.dataset.toggle is 
  // "#invoicing" or "#contact"
1 Like

Ah yes, that’s perfect. Thank you m3g4p0p

1 Like

Could I ask one more question with this, at the moment, they divs are open on load, what changes can I make to your code below to make it so the divs are closed on load, and then toggle to open when clicked.

$('[data-toggle]').click(function () {

F’shizzle my nizzle.

I wouldn’t do this with JS at all – just hide the divs with CSS as usual.

I went down the jscipt path to try and take advantage of the data-toggle bit as have multiple buttons and divs

But you can still toggle them with JS… the CSS only applies until it gets overridden by the JS adding inline styles (which is what .toggle() does).

.hidden {
  display: none;
<div id="invoicing" class="hidden">Lorizzle shiznit cool bizzle amizzle</div>
<div id="contact" class="hidden">Consectetuer adipiscing elit</div>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.