Saturday, May 3, 2014

Wordpress: jQuery accordion with 2 shortcodes

Update: Added the html example code too...

I recentry created a very simple accordion with jQuery in wordpress that can be inserted with shortcodes into any content.

The css:

 .title-div {  
      font-family: 'Roboto Condensed';  
      font-size: 23px;  
      color: #707070;  
      height: 53px;  
      line-height: 53px;  
      border-bottom: 1px solid #c5c6c8;  
      padding-left: 31px;  
      background-image: url(images/title-div-closed.gif);  
      background-position: left center;  
      background-repeat: no-repeat;  
 }  
 .title-div-opened {  
      font-family: 'Roboto Condensed';  
      font-size: 23px;  
      color: #90b13c;  
      height: 53px;  
      line-height: 53px;  
      border-bottom: 1px solid #c5c6c8;  
      padding-left: 31px;  
      background-image: url(images/title-div-opened.gif);  
      background-position: left center;  
      background-repeat: no-repeat;  
 }  
 .text-div {  
      font-size: 14px;  
      color: #707070;  
      line-height: 20px;  
      display: none;  
      padding-top: 15px;  
      padding-bottom: 15px;  
 }  

(Images are not included)

This goes in the theme's functions.php file:

 function titleDiv($atts, $string) {   
      return '<div class="title-div">'.$string.'</div>';   
 };   
 function textDiv($atts, $string) {   
      return '<div class="text-div">'.$string.'</div>';   
 };   
 function register_shortcodes() {   
      add_shortcode('title-div', 'titleDiv');   
      add_shortcode('text-div', 'textDiv');   
 };  

This is also needed, you can put it in the footer:

 jQuery(document).ready(function(){   
      $(".title-div").click(function() {   
           var wasOpen = false;  
           if($(this).hasClass("title-div-opened")) {  
                wasOpen = true;  
           }  
           $(".title-div-opened").next("div").slideUp();   
           $(".title-div-opened").attr("class", "title-div");   
           if(wasOpen == false) {  
                $(this).next("div").slideToggle();   
                $(this).toggleClass("title-div title-div-opened");   
           }  
           return false;   
      });   
 });   

The html you insert into the page should look something like this:

 <div class="title-div">Title 1</div>  
 <div class="text-div">Content 1</div>  

 <div class="title-div">Title 2</div>  
 <div class="text-div">Content 2</div>  

 <div class="title-div">Title 3</div>  
 <div class="text-div">Content 3</div>  

 <div class="title-div">Title 4</div>  
 <div class="text-div">Content 4</div>