Mihalma
Mihalma

Reputation: 101

How to show content from the specific div with javascript/jQuery

I want to show content from the specific div when the page loads. This is my code:

  $(document).ready(function () {
    $('.pbox:gt(0)').hide();
    $('#buttons').on('click', 'a', function () {
      $('.current').not($(this).closest('li').addClass('current')).removeClass('current');
      $('.pbox:visible').hide(600);
      $('.pbox[id=' + $(this).attr('data-id') + ']').show(600);

    });
  });
.current {
  background-color:red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<ul id="buttons">
   <li>
      <a data-id="div1">One</a>
   </li>
   <li>
      <a data-id="div2">Two</a>
   </li>
   <li>
      <a data-id="div3">Three</a>
   </li>
   <li class="current">
      <a data-id="div4">Four</a>
   </li>
</ul>

<div class="pbox" id="div1">
  Content 1
</div>
<div class="pbox" id="div2">
    Content 2
</div>
<div class="pbox" id="div3">
    Content 3
</div>
<div class="pbox" id="div4">
    Content 4
</div>

As you can see by default am adding the current class to the element:

<li class="current">
      <a data-id="div4">Four</a>
   </li>

So what am trying to achieve is when the page loads show Content 4 as you can see right now it shows Content 1 when the page loads.

Can anybody try to help me with this?

Upvotes: 0

Views: 52

Answers (1)

daremachine
daremachine

Reputation: 2788

If you need show content where link is active you can do it with code below

$.fn.pageLoad = function() {
  const currentId = $('li.current>a').data('id');
  $('.pbox:visible').hide(600);
  $('.pbox[id=' + currentId + ']').show(600);
}


$('document').pageLoad();

Just make any load function which close all pboxes and find current li>a id and open it. Also you can add setTimeout if your content is loading slow.

Upvotes: 1

Related Questions