Why Opt for Vanilla JavaScript Over jQuery To Turn Rank Math FAQ Block into an Accordion

Written By HarsH

6 min

752 Views

Why Opt for Vanilla JavaScript Over jQuery To Turn Rank Math FAQ Block into an Accordion

In today’s digital landscape ๐ŸŒ, over a million people are using Rank Math SEO plugin to optimize their WordPress websites and blogs. While Rank Math provides a number of features ๐Ÿ› ๏ธ, one that stands out is its FAQ schema block, complete with built-in FAQ schema capabilities ๐ŸŒŸ.

However, this feature comes with its own set of limitations โŒ: a lack of customization options and uninspiring design elements.

But fear not ๐Ÿ˜Œ, in this post, we’ll guide you through the process of transforming your Rank Math FAQ block into a more dynamic, performance optimized and visually appealing accordion format ๐ŸŒˆ. Stay tuned ๐Ÿ“บ to discover how you can add a touch of sophistication and functionality to your website’s FAQ section ๐ŸŽจ.

But why transform? ๐Ÿค” Accordions are a popular way to display frequently asked questions (FAQs), especially for websites aiming to offer a user-friendly experience without overwhelming the visitor with too much information at once ๐Ÿ“š.

However, the efficiency of the code powering these accordions can vary significantly โš–๏ธ, especially when comparing Vanilla JavaScript with jQuery-based solutions. In this blog, we’ll examine a specific case study to understand why Vanilla JavaScript could be a more optimized choice ๐Ÿš€.

The Problem

The task is simple ๐ŸŽฏ: convert Rank Math’s FAQ block into an accordion. While Rank Math’s official blog ๐Ÿ“ offers a guide on how to do this, it uses jQuery. We’ve opted for a different route ๐Ÿ›ค๏ธ for reasons, including performance and SEO benefits. In this post ๐Ÿ“ฎ, we’re providing a revamped guide that uses Vanilla JavaScript instead ๐ŸŒŸ.

Here is a snippet of the original jQuery-based code:

/**
 * Convert Rank Math FAQ Block Into Accordion
 */
function turn_rm_faq_to_accordion() {
	?>
	<script>
		jQuery(document).ready(function() {
			var faqBlock = jQuery("div#rank-math-faq");
			var faqItems = faqBlock.find("div.rank-math-list-item");
			faqItems.bind("click", function(event) {
				var answer = jQuery(this).find("div.rank-math-answer");
				if (answer.css("overflow") == "hidden") {
					answer.css("overflow", "visible");
					answer.css("max-height", "100vh");
				} else {
					answer.css("overflow", "hidden");
					answer.css("max-height", "0");
				}
			});
		});
	</script>
	<?php
}
add_action( 'wp_footer', 'turn_rm_faq_to_accordion' );

Why Vanilla JavaScript?

  1. No Dependencies

Vanilla JavaScript doesn’t require any external libraries. This decreases the page load time, which is a critical factor for user experience and SEO rankings.

  1. Performance

JavaScript engines in modern browsers are optimized for Vanilla JavaScript. This means faster execution and better memory management.

  1. Better Control

Vanilla JavaScript allows for more fine-grained control over the DOM and events, leading to more optimized solutions.

The Vanilla JavaScript Solution

Here is an optimized version using Vanilla JavaScript:

/**
 * Convert Rank Math FAQ Block Into Accordion using Vanilla JavaScript optimized by PBT
 */
function rm_faq() {
    global $post;

    // Check if current page is a post or a page
    if( is_single() || is_page() ) {

        // Check if the post has the Rank Math FAQ block
        if( has_block( 'rank-math/faq-block', $post ) ) {
            ?>
<script>document.addEventListener("DOMContentLoaded",function(){const a=new Map;document.querySelectorAll(".rank-math-block .rank-math-list-item").forEach(t=>{var e=t.querySelector(".rank-math-question");const s=t.querySelector(".rank-math-answer");s.classList.add("hidden"),a.set(e,s)}),document.body.addEventListener("click",function(t){if(t.target.classList.contains("rank-math-question")){const s=t.target,e=a.get(s);e.classList.toggle("hidden"),e.classList.toggle("collapse"),a.forEach((t,e)=>{e!==s&&(t.classList.add("hidden"),t.classList.remove("collapse"),e.classList.remove("collapse"))}),s.classList.toggle("collapse")}})});</script>
<style>
#rank-math-faq .rank-math-list-item{margin-bottom:1em;margin-top:1em;border-bottom:1px solid #fff}.rank-math-question{cursor:pointer;position:relative;display:block;padding-right:1em;margin-right:1em;font-weight:300;margin-top:30px;will-change:transform}.rank-math-question:after{position:absolute;right:5px;top:0;content:"\2715";transform:rotate(-45deg);transition:transform 150ms ease-in-out}.rank-math-question.collapse:after{transform:rotate(0)}.rank-math-question:hover{opacity:.8}.rank-math-answer{display:none;transition:max-height .2s ease-out;overflow:hidden;max-height:0}.rank-math-answer.collapse{display:block;max-height:200px;transition:max-height .25s ease-in}
</style>
<?php
}
add_action('wp_footer', 'rm_faq');

How to Implement?

  1. Log in to your WordPress admin dashboard.
  2. Navigate to Plugins > Add New.
  3. In the search bar, type “WPCode” and install.
  4. After installation, click Activate to enable the plugin on your site.
  5. Once activated, you’ll see a new menu item named Code Snippets in your WordPress admin sidebar.
  6. Click on it to open the plugin interface.
  7. Within the plugin interface, click on Add New Snippet to create a new code snippet and click on Add Your Custom Code.
  8. You’ll see a text editor, select “Code TypePHP Snippet“.
  9. Copy and paste the above PHP code into the text editor.
  10. Then, scroll down and select Insert Method – “Auto Insert
  11. In the location option, select “Frontend Only“.
  12. And lastly, turn on “Enable Logic” and select “Show“, “Post type Is Posts” – This is important as it will help to load this accordion function only on blog posts where Rank Math FAQ block is added.
  13. Finally, click on activate and save the snippet. And boom, your Rank Math FAQ block has been converted to beautiful and optimized accordion block.

What Makes the Vanilla JavaScript Code Better?

  1. Reduced DOM Traversal

In the Vanilla JavaScript code, we use a Map to store questions and their corresponding answers. This minimizes the number of times the DOM is traversed, making the code faster and more efficient.

  1. Event Delegation

The use of event delegation further reduces the number of event listeners attached to the DOM elements. This is better for memory usage and event handling performance.

  1. Class Toggling

Instead of manipulating inline styles, which can get messy and is generally not recommended, the new code uses CSS classes for visibility and state management. This is generally faster and leads to cleaner, more maintainable code.

  1. SEO Impact

Faster and more efficient client-side code can contribute to a better user experience, which is a factor in SEO rankings. Though the JavaScript code itself is not directly evaluated by search engines, its impact on user experience and page load time is considered.

Conclusion

While jQuery was revolutionary in its time โณ, modern Vanilla JavaScript offers robust capabilities ๐Ÿ’ช that allow us to write more efficient and performant code. This is critical ๐ŸŽฏ for improving user experience and SEO rankings, especially for businesses aiming for optimal web presence ๐ŸŒ.

In our case study ๐Ÿ“Š, switching to Vanilla JavaScript for accordion functionality led to better performance, cleaner code โœจ, and potentially improved SEO ๐Ÿ“ˆ. Therefore, it’s worth considering Vanilla JavaScript over jQuery for similar tasks in your web development projects ๐Ÿ‘ฉโ€๐Ÿ’ป.

About the author

HarsH

2 thoughts on “Why Opt for Vanilla JavaScript Over jQuery To Turn Rank Math FAQ Block into an Accordion”

  1. Hey,
    great approach with no jQuery! Unfortunately I get an error, when I paste the code into WP Code Snippits (same functionality as WPCode) that reads:

    “Snippet automatically deactivated due to an error on line 19:
    Unclosed ‘{‘ on line 8.”

    Unfortunately, I don’t really know anything about programming. Maybe you can look into it?
    Thanks!
    ~ Julian

    Reply

Leave a Comment