jQuery Tip: Scroll to the top of active accordion items whenever a new item is expanded (with the option to account for a fixed header)

Here is a really handy tip on how to add functionality for a user to be scrolled to the top of the currently active accordion item whenever a new accordion item is expanded. The key here, and the one that I have spent more hours than I care to remember trying to figure out, is to calculate in the the height of the already-open-but-now-closing accordion item.

Let’s assume your HTML markup looks something like this:

<div class="accordionWrapper">
<div class="accordionButton" id="id1">Accordion #1 Title</div>
<div class="accordionContent">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut accumsan erat eleifend ipsum hendrerit mattis. Pellentesque in urna non eros fringilla suscipit et quis velit. Pellentesque pulvinar hendrerit interdum. Morbi scelerisque est rutrum, porttitor odio sed, interdum velit. Sed lobortis, nulla vitae tincidunt varius, diam metus malesuada odio, at commodo nunc sem vitae justo. Sed eu eros a lorem feugiat blandit eu id arcu. Curabitur ultrices massa vitae tempor lacinia. Integer ac ligula elit. Aenean vel porta nisl. Aliquam ac justo erat.
</div>
</div>
<div class="accordionButton" id="id2">Accordion #2 Title</div>
<div class="accordionContent">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut accumsan erat eleifend ipsum hendrerit mattis. Pellentesque in urna non eros fringilla suscipit et quis velit. Pellentesque pulvinar hendrerit interdum. Morbi scelerisque est rutrum, porttitor odio sed, interdum velit. Sed lobortis, nulla vitae tincidunt varius, diam metus malesuada odio, at commodo nunc sem vitae justo. Sed eu eros a lorem feugiat blandit eu id arcu. Curabitur ultrices massa vitae tempor lacinia. Integer ac ligula elit. Aenean vel porta nisl. Aliquam ac justo erat.
</div>
</div>
</div>

Here is the jQuery you can take and recycle as you see fit:

$(document).ready(function() {
$('.accordionButton').click(function() {
  	var thisParent = $(this).parent();
  	var trigger = $(this);  
  	var openAccordionHeight = $(thisParent).prevAll('.active').children().eq(1).outerHeight();
       if ($(thisParent).hasClass('active')) {
	        $(this).next().slideUp('normal');
	        $(thisParent).removeClass('active');
	        return;
       } 
       $('.accordionContent').slideUp('slow');
       $('.active').removeClass('active');
       $(thisParent).addClass('active');
       $('html,body').animate({scrollTop: $(trigger).offset().top-openAccordionHeight}, 500);
       $(trigger).next().slideDown(500);
   });

});

And here is the code to use if you have a fixed header and need to calculate that in as well:

$(document).ready(function() {
$('.accordionButton').click(function() {
   	var headerHeight = $('.header').outerHeight();
  	var thisParent = $(this).parent();
  	var trigger = $(this);  
  	var openAccordionHeight = $(thisParent).prevAll('.active').children().eq(1).outerHeight();
       if ($(thisParent).hasClass('active')) {
	        $(this).next().slideUp('normal');
	        $(thisParent).removeClass('active');
	        return;
       } 
       $('.accordionContent').slideUp('slow');
       $('.active').removeClass('active');
       $(thisParent).addClass('active');
       $('html,body').animate({scrollTop: $(trigger).offset().top-openAccordionHeight-headerHeight}, 500);
       $(trigger).next().slideDown(500);
   });

});

Royal Slider: Play video when clicking anywhere in the preview image

Here is the code I use to play a YouTube or Vimeo video in a Royal Slider gallery when a visitor clicks anywhere in the preview image, and not just when they click the Play button itself:

<script>
jQuery(document).ready(function($) {
    $('.royalSlider').each(function() {
      var slider = $(this);
      $('.rsContainer').click(function() {
        slider.royalSlider('playVideo');
      });
    });
});
</script>

WordPress Tips: Adding keyboard navigation between posts

I used the tips in this helpful post today to add keyboard navigation between posts on a WordPress website.

The jQuery script is:

(function($){
   $(document).ready(function () {
      $(document).keydown(function(e) {
         var url = false;
         if (e.which == 37) {  // Left arrow key code
            url = $('.prev a').attr('href');    }
         else if (e.which == 39) {  // Right arrow key code
            url = $('.next a').attr('href');    }
         if (url) { window.location = url;   }
     });
   });
})(jQuery);

Then, just make sure your previous and next post links have the appropriate classes:

<div class="prev-next">
<div class="alignleft prev"><?php previous_post('&laquo; %', '', 'yes'); ?></div>
<div class="alignright next"><?php next_post('% &raquo; ', '', 'yes'); ?></div>
</div>

How to fade in content on page scroll on a website that uses fullPage.js with CSS and jQuery

I recently used the fullPage.js script on a website that I am working on and ran into a bit of trouble getting the section content to fade in nicely when it was scrolled into view. Here is the way I was able to accomplish that feature.

Following the instructions on how to incorporate fullPage.js into my site, my HTML structure looked like this:

<div id="fullpage">
    <div class="section">Some section</div>
    <div class="section">Some section</div>
    <div class="section">Some section</div>
    <div class="section">Some section</div>
</div>

First, I added this declaration to my stylesheet, to start all of the page sections out as invisible:

.section {
	opacity:0;
}

Next I found the onattrchange listener (a jQuery plugin). I downloaded this script – https://raw.github.com/meetselva/attrchange/master/attrchange.js – and uploaded to it to my website, and then added the call to it into my webpage, after my call to the jQuery library:

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="/scripts/attrchange.js"></script>

*Note: make sure to verify that the path to your script in the code above is correct!

And then, finally I added this bit of jQuery to my webpage:

<script>
$(document).ready(function(){

$(".section").eq(0).animate({"opacity":"1"},1500);  //fade the first div.section in on page load

$(".section").attrchange({
    trackValues: true, // set to true so that the event object is updated with old & new values
    callback: function(evnt) {
        if(evnt.attributeName == "class") { // which attribute you want to watch for changes
            if(evnt.newValue.search(/active/i) == -1) { // "active" is the class name you search for inside "class" attribute
                $(".section.active").animate({"opacity":"1"},1500); //fade in the section with class active
            }
        }
    }
});

}); //end of document ready
</script>

And that did the trick! Now my section content fades in nicely when the new section is scrolled into view.

Open and scroll to an anchor link on a different page with an offset to adjust for a fixed header

Here is the script I have used to open and scroll to an anchor link on a different page on a site that has a fixed header and therefore needs to have an offset so the anchor link is not hidden behind the header.

<script>
$(document).ready(function() {
var offsetSize = $(".header").innerHeight();
$("html, body").animate({scrollTop:$(window.location.hash).offset().top-offsetSize }, 500);
});
</script>

What this script is doing is calculating the height of your fixed header (in this case: div.header) and then, upon loading the new page, scrolling to the correct anchor link on the page with an offset that is equal to the height of your fixed header.

In order for this script to work properly, you need to add an ID to your anchor link names that is the same as their name. For example:

<a name="contact" id="contact"></a>

How to make the top-level links in a jQuery accordion menu clickable

I often use a jQuery accordion menu for the mobile menu on responsive websites and have run into issues before where the top level links by default seem only to expand or collapse submenus and not actually take you to the page you are trying to go to. What I have found is that I usually just need to add this line of code to my script:

header: '.menu-control'

So, for example, the script I now use to call in the accordion menu would be:

function enableAccordion() {
 $('#menu-mobile-nav').accordion({
 header: '.menu-control',
 autoHeight: false,
 navigation: true,
 collapsible: true,
 active: false
 });
}

Where my HTML for the menu is:

<h3>MENU</h3>
<ul id="menu-mobile-nav" class="menu">
<li><a href="/">Home</a></li>
<li><a href="/about">About Us</a></li>
<li><a href="/contact">Contact Us</a></li>
</ul>

Combine the values of two fields in a form into one variable to be inserted into MySQL database table

Here is the simple code that I use to combine the values of two fields in a form into one variable and insert that variable into a database table.

One example of how I used this trick was when I built an SMS-subscriber widget for a website. I needed people to enter their phone numbers into one field, select their phone carrier from another field, and then combine those two fields with an “@” symbol in between to create an email address that was then inserted into the database. These SMS subscribers could then receive the same notice as email subscribers.

Here is the code you use:

<script>
$('#insert').bind('submit', function(){
                        var phone = $('[name=phone]').val();
                        var email = $('[name=email]').val();
                        $('[name=subscriber]').val(phone+'@'+email);
                      });
</script>

Note: #insert in the code above needs to be changed to the id of your form. 

Insert the jQuery code above directly after the beginning of your form, which would look something like this:

<form action="insert.php" method="POST" id="insert">

Next, create a hidden field which will contain the combined values of the two fields:

<input type="hidden" name="subscriber"/>

And finally, create the two fields whose values you want to combine:

Phone #: <input type="text" size=25 name="phone">
Carrier: <select>
  <option name="email" value="vtext.com">Verizon</option>
  <option name="email" value="txt.att.net">AT&T</option>
</select>

In the php file that you use to process the form, you will only need to post the data from the hidden field (which contains the values of the two fields). For instance, using the example above, I would only insert the ‘subscriber’ data into the database:

$v_subscriber=$_POST['subscriber'];
... 
$query="insert into table_name(email) values('$v_subscriber')";

This would insert the value of the subscriber field (which is “phone@email” according to the jQuery above. For example: 1234567890@att.txt.net) into the email column of the table you specified.

Please let me know if you have questions or run into any issues at all.

A simple tabbed navigation menu created with CSS, HTML, and jQuery

Here are the codes that I use to create a tabbed navigation menu for a website.

You can see a demo of the tabbed menu here.

First, copy and paste this block of code into your stylesheet:

ul.tabs {
margin: 0;
padding: 0;
float: left;
list-style: none;
height: 32px; /*--Set height of tabs--*/
border-bottom: 1px solid #999;
border-left: 1px solid #999;
width: 100%;
}

ul.tabs li {
float: left;
margin: 0;
padding: 0;
height: 31px; /*--Subtract 1px from the height of the unordered list--*/
line-height: 31px; /*--Vertically aligns the text within the tab--*/
border: 1px solid #999;
border-left: none;
margin-bottom: -1px; /*--Pull the list item down 1px--*/
overflow: hidden;
position: relative;
background: #e0e0e0;
}

ul.tabs li a {
text-decoration: none;
color: #000;
display: block;
font-size: 1.2em;
padding: 0 20px;
border: 1px solid #fff; /*--Gives the bevel look with a 1px white border inside the list item--*/
outline: none;
}

ul.tabs li a:hover {
background: #ccc;
}

html ul.tabs li.active, html ul.tabs li.active a:hover  { /*--Makes sure that the active tab does not listen to the hover properties--*/
background: #fff;
border-bottom: 1px solid #fff; /*--Makes the active tab look like it's connected with its content--*/
}

.tab_container {
border: 1px solid #999;
border-top: none;
overflow: hidden;
clear: both;
float: left; width: 100%;
background: #fff;
}

.tab_content {
padding: 20px;
font-size: 1.2em;
color:#333;
}
Then, copy and paste this block of code into your web page where you want the tabbed menu to appear:


   
        Content of the first tab    
   
       Content of the second tab    
[/code]
Now, copy and paste this block of code into the section of your web page:
<script type="text/javascript" src="<a href="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" target="_blank">http://ajax.googleapis.<wbr>com/ajax/libs/jquery/1.3/<wbr>jquery.min.js</wbr></wbr></a>"></script>
<script type="text/javascript">
$(document).ready(function() {
//Default Action
$(".tab_content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").<wbr>show(); //Activate first tab $(".tab_content:first").show()<wbr>; //Show first tab content //On Click Event $("ul.tabs li").click(function() { $("ul.tabs li").removeClass("active"); //Remove any "active" class $(this).addClass("active"); //Add "active" class to selected tab $(".tab_content").hide(); //Hide all tab content var activeTab = $(this).find("a").attr("href")<wbr>; //Find the rel attribute value to identify the active tab + content $(activeTab).fadeIn(); //Fade in the active content return false; }); }); </script></wbr></wbr></wbr>
Now, all you will need to do is style the menu the way you want and add your content to the different tabs.
Let me know if you have any questions or run into any issues with this.