Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7519239
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T01:52:10+00:00 2026-05-30T01:52:10+00:00

How can I toggle the content div on/off when I click on the ‘toggle’

  • 0

How can I toggle the content div on/off when I click on the ‘toggle’ text?

<div class="toggle col">TOGGLE

  <div class="content-to-toggle">
    content
  </div>
</div>

Is there a lighter version than this one:

document.addEventListener('click', function(e){
  if(e.target.className.indexOf('toggle') !== -1)
    e.target.className = e.target.className.replace(/\bexp\b|\bcol\b/, function(m){ return m == 'col' ? 'exp' : 'col'; });
});

?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T01:52:11+00:00Added an answer on May 30, 2026 at 1:52 am

    That function has a few flaws:

    1. addEventListener will fail in browsers like IE 8 and lower
    2. e.target will fail in browsers like IE 8 and lower
    3. indexOf('toggle') will match toggle anywhere in the class value, probablly better to use a regualr exprssion like: /(^|\s)toggle(\s|$)/
    4. replace(/\bexp\b|\bcol\b/ uses word breaks as the delimiter, but class values are separated by spaces, not word breaks (like hyphen)

    Lastly, what do you mean by “ligther”? Less code? Faster? Uses fewer resources?

    Edit

    A better version of the function would use:

    1. a cross-browser method of attaching the listener (there are many generic addListener functions around)
    2. a generic method of determining if the class value should be toggled (a simple hasClass function)
    3. a generic method of removing one class value and adding the other (simple removeClass and addClass functions)

    Also there should be a fork to say what to do if the element doesn’t have either of the classes—should it default to one or the other or do nothing?

    So here’s an example:

    <title>Toggling Example</title>
    
    <style type="text/css">
      .exp {background-color: #666666;}
      .col {background-color: #bbbbbb;}
    </style>
    
    <script type="text/javascript">
    
    // Generic container for utility functions
    var util ={};
    
    util.trim = function(s) {
      return s.replace(/(^\s+)|(\s+$)/g,'').replace(/\s+/g,' ');
    }
    
    // Generic container for DOM functions
    util.dom = {};
    
    util.dom.hasClass = function(el, cName) {
        var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)');
        return el && re.test(el.className);
    };
    
    util.dom.addClass = function(el, cName) {
        if (!util.dom.hasClass(el, cName)) {
            el.className = util.trim(el.className + ' ' + cName);
        }
    };
    
    util.dom.removeClass = function(el, cName) {
        if (util.dom.hasClass(el, cName)) {
            var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)','g');
            el.className = util.trim(el.className.replace(re, ''));
        }
    }
    
    // Generic container for DOM event functions
    util.event = {};
    
    util.event.addListener = function(el, evt, fn) {
      if (el.addEventListener) {
        el.addEventListener(evt, fn, false);
      } else if (el.attachEvent) {
        el.attachEvent('on' + evt, fn);
      }
    }
    
    function toggleClass(el, c0, c1) {
    
      // Replace c0 with c1
      if (util.dom.hasClass(el, c0)) {
        util.dom.removeClass(el, c0);
        util.dom.addClass(el, c1);
    
      // Replace c1 with c0
      } else if (util.dom.hasClass(el, c1)) {
        util.dom.removeClass(el, c1);
        util.dom.addClass(el, c0);
    
      // If doesn't have either class, add c0
      } else {
        util.dom.addClass(el, c0);
      }
    }
    
    // Is this "light" enough?
    window.onload = function() {
      util.event.addListener(document.body, 'click', function(e) {
        var e = e || window.event;
        var el = e.target || e.srcElement;
        toggleClass(el, 'exp', 'col');
      });
    }
    
    </script>
    
    <div>foo bar</div>
    

    Edit 2

    “Less code” is never a good reason to do anything, though it is a reasonable objective where it doesn’t obfuscate or reduce clarity. In any case, here is a “better” version of your original:

    document.addEventListener('click', function(e){
       var el = e.target, cn = el.className;
       if(/(^|\s)toggle(\s|$)/.test(cn))
         el.className = cn.replace(/(^|\s)exp|col(\s|$)/, function(m){ return m == 'col' ? 'exp' : 'col';});
    });
    

    It is a bit more efficient and uses a standard delimiter for class name values.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How can I compact the jQuery Code Below? //FIRST CODE jQuery('.expand-two').click(function(){ jQuery('.content-two').slideToggle('fast'); }); jQuery('.expand-two').toggle(function()
How can I toggle script/content in page using browser action button? Example: click browser_action
How can i toggle a div closed using jquery ie hide the box below
// accordion $(#left-nav .block h2).click(function(){ $(this).next(div).slideToggle(fast, function() { alert(hey); $(#left-nav, #content, #aside).equalHeight(); }) .siblings(div:visible).slideUp(fast);
I'm using Soh Tanaka's script to toggle open and closed div content in the
I have the following markup <div class=question> <h2>Title 1</h2> <div class=answer>content 1</div> </div> <div
I already have the scroll to and toggle functions in place: $(a.view).click(function(){ $(#content).slideToggle(slow); return
The javascript code I now have can toggle a single row of data. Whether
Can anyone explain why the following jquery only fires the 2nd toggle event and
How can I create in a Swing interface a toggle image button? I have

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.