Click here to Skip to main content
15,878,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have built a accordion, and I want to have the first item open on page load.
How can I do this with Jquery?

This is my code:
<script>
  $(document).ready(function(){
    $(".accordion_header").click(function() {
      $(".accordion_header").removeClass("active");
      $(this).addClass("active");
    })
  });
</script>


Html:

<div class="wrapper">
       <div class="accordion_wrap">
         <div class="accordion_header">
           <h5>INFO</h5>
         </div>
         <div class="accordion_body">
         <p>Lorem ipsum dolor sit amet,<br>
         consectetur adipiscing elit. <br></p>
         </div>
       </div>
       <div class="accordion_wrap">
         <div class="accordion_header">
           <h5>INFO</h5>
         </div>
         <div class="accordion_body">
         <p>Lorem ipsum dolor sit amet,<br>
         consectetur adipiscing elit. <br></p>
         </div>
       </div>
       <div class="accordion_wrap">
         <div class="accordion_header">
           <h5>INFO</h5>
         </div>
         <div class="accordion_body">
         <p>Lorem ipsum dolor sit amet,<br>
         consectetur adipiscing elit. <br></p>
         </div>
       </div>
     </div>


css is very long and I guess unnecessary.

Thanks,
Sam

What I have tried:

Tried to search the internet, and I have the code above.
Posted
Updated 18-Nov-20 22:19pm
Comments
[no name] 18-Nov-20 12:59pm    
What gets loaded now if not "first"?
Sam Vorst 18-Nov-20 13:07pm    
They are all closed now.

1 solution

Either add the active class to the first item in the markup:
HTML
<div class="accordion_wrap">
    <div class="accordion_header active">
        <h5>INFO</h5>
    </div>
or add it via script:
JavaScript
$(function(){
    $(".accordion_header").click(function() {
        $(".accordion_header").removeClass("active");
        $(this).addClass("active");
    });
    
    $(".accordion_header:first").addClass("active");
});

NB: Pay attention to the documentation:

jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:
  • $( handler )
  • $( document ).ready( handler )
  • $( "document" ).ready( handler )
  • $( "img" ).ready( handler )
  • $().ready( handler )

As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated.
 
Share this answer
 
Comments
Sam Vorst 19-Nov-20 5:50am    
Thanks!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900