Advertisement
Theme Development

Creating a WordPress Post Text Size Changer Using jQuery

by

We already know that WordPress is considered the most popular CMS in the world and when it combines with jQuery, it can create wonders. In this tutorial we shall be discussing one example of the usefulness of jQuery in WordPress, by creating a front-end post text size changer. This tutorial is aimed at beginners who are learning to introduce the magic of jQuery in WordPress.


What Are We Actually Going to Create

In this tutorial we are going to create a front-end text size changer that alters the font size of the posts as per the reader's convenience. Suppose you are on a blog reading a post and you find it tough traversing through the lines of the post because of the text size. Here comes the need of the text size changer to increase/decrease the text size of the post accordingly. Increasing/Decreasing font size is generally considered due to a number of factors such as:

  • To adjust the text as per your screen resolution
  • To alter the default text size shown by the browser
  • To increase clarity of words
  • More convenient than the use of Ctrl+ or Ctrl- in your browser
  • For visually impaired persons who are unable to read smaller fonts

In this tutorial we will be creating two links, A+ and A-, in the front-end which will increase or decrease the text size of the post accordingly with ease.


Step 1: Decide Which Part to Resize

This is the most important step in which you have to decide which element you want to associate with the text size changer. Though you can put the text size changer in the home page (index) itself, it is considered wise to put it in the single.php page to be utilized while viewing a single post.

In order to make an element resizable we have to wrap that part using a unique div class. Since we are using the Twenty Twelve theme, here is what our 'single.php' file looks like after adding the code highlighted below to wrap the post within the 'resize' class.


<?php
/**
 * The Template for displaying all single posts.
 *
 * @package WordPress
 * @subpackage Twenty_Twelve
 * @since Twenty Twelve 1.0
 */

get_header(); ?>


	<div id="primary" class="site-content">
		<div id="content" role="main">
		    <div class="resize">

			<?php while ( have_posts() ) : the_post(); ?>

				<?php get_template_part( 'content', get_post_format() ); ?>
				
		    </div><!-- #resize -->

				<nav class="nav-single">
					<h3 class="assistive-text"><?php _e( 'Post navigation', 'twentytwelve' ); ?></h3>

					<span class="nav-previous"><?php previous_post_link( '%link', '<span class="meta-nav">' . _x( '&larr;', 'Previous post link', 'twentytwelve' ) . '</span> %title' ); ?></span>

					<span class="nav-next"><?php next_post_link( '%link', '%title <span class="meta-nav">' . _x( '&rarr;', 'Next post link', 'twentytwelve' ) . '</span>' ); ?></span>

				</nav><!-- .nav-single -->

				<?php
					// If comments are open or we have at least one comment, load up the comment template
					if ( comments_open() || '0' != get_comments_number() )
						comments_template( '', true );
				?>

			<?php endwhile; // end of the loop. ?>

		</div><!-- #content -->
	</div><!-- #primary -->

<?php get_sidebar(); ?>

<?php get_footer(); ?>

Here we have placed the div class resize in such a way that it considers only the body of a single post.

For any element in WordPress for which you want the resizeble text, just wrap it within proper div classes to be used with jQuery.


Step 2: Adding the Links to Resize Text

The next step is to add the two links in the page which will act as two buttons to resize the text. You can place them anywhere within your page but avoid placing them within the loop. Here we have placed them in our single.php file and have associated them with two unique IDs.



<?php
/**
 * The Template for displaying all single posts.
 *
 * @package WordPress
 * @subpackage Twenty_Twelve
 * @since Twenty Twelve 1.0
 */

get_header(); ?>


	<div id="primary" class="site-content">
		<div id="content" role="main">
		     <div class="resize">

			<?php while ( have_posts() ) : the_post(); ?>

				<?php get_template_part( 'content', get_post_format() ); ?>
				
		      </div><!-- #resize -->

				<nav class="nav-single">
					<h3 class="assistive-text"><?php _e( 'Post navigation', 'twentytwelve' ); ?></h3>
					<span class="nav-previous"><?php previous_post_link( '%link', '<span class="meta-nav">' . _x( '&larr;', 'Previous post link', 'twentytwelve' ) . '</span> %title' ); ?></span>

					<span class="nav-next"><?php next_post_link( '%link', '%title <span class="meta-nav">' . _x( '&rarr;', 'Next post link', 'twentytwelve' ) . '</span>' ); ?></span>

				</nav><!-- .nav-single -->

				<?php
					// If comments are open or we have at least one comment, load up the comment template
					if ( comments_open() || '0' != get_comments_number() )
						comments_template( '', true );
				?>

			<?php endwhile; // end of the loop. ?>

		</div><!-- #content -->
	</div><!-- #primary -->
<p><a id="increase-font" href="#">[ A+ ] </a>/<a id="decrease-font" href="#">[ A- ] </a> </p>
<?php get_sidebar(); ?>

<?php get_footer(); ?>

Step 3: Adding the jQuery Magic

Now it's time to add the jQuery magic to our theme in order to make the two increase/decrease links function. Under your theme's js folder create a JavaScript file named resize.js. Now open the file and add the following piece of code. The code is clearly explained using the comments.

// This prevents the execution of the code before the document is finished loading.
jQuery(document).ready(function() {

	// The 'A+' element  in the page is associated with the jQuery click() event.
	jQuery('#increase-font').click(function(event) {

		// This prevents the default action of the click() event from being triggered.
		event.preventDefault();
		// The jQuery each() event interates over each elements belonging to the 'resize' class
		jQuery('.resize').each(function() {
			// Call to a custom function to increase the text size
			changeTextSize(this, change);
		});
	});

	// The 'A-' element  in the page is associated with the jQuery click() event.
	jQuery('#decrease-font').click(function(event) {

		// This prevents the default action of the click() event from being triggered.
		event.preventDefault();
		// The jQuery each() event interates over each elements belonging to the 'resize' class
		jQuery('.resize').each(function() {
			// Call to a custom function to decrease the text size
			changeTextSize(this, -change);
		});
	});
});

// Three variables have been used to define range of the text size and the increment/decrement value respectively.
var min = 8, max = 100, change = 2;

// Defines a custom function with two parameters determining the element to be resized and the size
function changeTextSize(element, value) {
	var currentSize = parseFloat(jQuery(element).css('font-size'));
	var newSize = currentSize + value;
	if (newSize <= max && newSize >= min) {
		jQuery(element).css('font-size', newSize + 'px');
	}
}

If you like to learn more about jQuery please check out the Learn jQuery in 30 Days tutorial series by Jeffrey Way.


Step 4: Referencing the Script in WordPress

This is the final step in which we need to add a reference to the resize.js script in WordPress so that it executes the code. By default the WordPress installation already contains the jQuery library. We just need to reference the script within the theme. Open your functions.php file and add the following code snippet.

function wptuts_resize_text () {
	// The array('jquery') is used to create dependency on the jQuery library in order to use it properly.
	wp_enqueue_script( 'resize', get_template_directory_uri() . '/js/resize.js', array( 'jquery' ) );
}
add_action( 'wp_enqueue_scripts', 'wptuts_resize_text' );

That's it. Now if you are viewing a post, you can increment or decrement the font size of the post using the A+ and A- links in the page. You can use your own CSS to properly style and place the two links in your website as you see fit.

Related Posts
  • Code
    Theme Development
    Custom Controls in the Theme CustomizerTheme customizer custom control 400
    In the last article, we explored the advanced controls available in the Theme Customizer, and how to implement them. We’re going to look at how to create our own custom control, allowing you to choose which Category of Posts are displayed on the home page. To get started, download version 0.6.0 of our Theme Customizer Example.Read More…
  • Code
    Theme Development
    Creating a WordPress Theme From Static HTML: The Footer FileCreating wordpress theme from html 400
    In this series, you've been learning how to create a WordPress theme form static HTML. Up to this point, you have: prepared your markup for WordPress converted your HTML to PHP and split your file into template files edited the stylesheet and uploaded your theme to WordPress added a loop to your index file added meta tags, the wp_head hook and the site title and description to your header file added a navigation menu added widget areas to the header and sidebar. Read More…
  • Web Design
    Case Studies
    How They Did It: Typekit's New HomepageTypekit retina
    Typekit recently redesigned their homepage with some new services in mind. When Typekit joined Adobe, they set out to bring us a new way to handle fonts on the web. Not only did they create a fairly simple way to embed fonts on the web, but they have now officially launched a desktop sync option, which allows Creative Cloud subscribers to sync fonts to their computer directly from Typekit. This has been in a beta form for a while now, and provides a much easier route to local fonts than finding them elsewhere!Read More…
  • Web Design
    UX
    Walk Users Through Your Website With Bootstrap TourTour retina
    When you have a web application which requires some getting used to from your users, a walkthrough of the interface is in order. Creating a walkthrough directly on top of the interface makes things very clear, so that's what we're going to build, using Bootstrap Tour.Read More…
  • Code
    PHP
    Creating a Photo Tag Wall With Twilio Picture Messaging & PHPProcedural to oop php retina preview
    Twilio's recently announced Picture Messaging has vastly opened up what we can do with text messaging, now we can attach photos to our text messages and have them get used in different ways. In our case, we are going to build a Photo Tag Wall, which will contain photos linked to tags that will be displayed on a website.Read More…
  • Code
    Theme Development
    Creating a WordPress Theme From Static HTML: Creating Template FilesCreating wordpress theme from html 400
    In the first part of this series, I showed you how to prepare your HTML and CSS files for WordPress, ensuring the structure would work, the code was valid and that the correct classes were being used. In this tutorial you'll learn how to take your index.html file and split it up into a set of template files for use by WordPress.Read More…