Search code examples
jquerytwitter-bootstrapbootstrap-accordion

Jquery: how check if an element is visible inside a Boostrap collapsed accordion


I need to check the visibility on an element inside a Boostrap collapsed accordion.

This element is set to "display:none" under certain circumstances by JQuery Validator, and I need to add some further controls depending on its display settings - as I've encountered a weird behaviour with its functionality in the form I've set and I'm trying to find a different approach.

Obliviously, the problem is that elements inside a collapsed accordion aren't visible, so I don't know how control that property.

The element is:

<span id="edit-field-attachments-und-0-upload--2-error" class="error">Campo obbligatorio</span>

So, if I try something like to use:

$('.panel span.error:visible')

or equivalent selectors, I don't get a correct result unless the accordion is opened.

Any idea how solve this situation? Thanks


Solution

  • You could try this, to see if the element exists in the dom as an inline element. If you add style="display: none;" to the span tag to test, you should see that the isVisible will return "none", which you can then add logic to say if the span is inline or none, etc..

    function isVisible(el) {
      return window.getComputedStyle(el[0]).display;
    }
    
    console.log(isVisible($('#collapse1 .error')));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    
    <div class="container">
      <h2>Collapsible Panel</h2>
      <p>Click on the collapsible panel to open and close it.</p>
      <div class="panel-group">
        <div class="panel panel-default">
          <div class="panel-heading">
            <h4 class="panel-title">
              <a data-toggle="collapse" href="#collapse1">Collapsible panel</a>
            </h4>
          </div>
          <div id="collapse1" class="panel-collapse collapse">
            <div class="panel-body"><span id="edit-field-attachments-und-0-upload--2-error" class="error">Campo obbligatorio</span></div>
            <div class="panel-footer">Panel Footer</div>
          </div>
        </div>
      </div>
    </div>