Show more/less of the text snippet and main body of information

I am currently in the process of setting up a basic WordPress blog with only one page dedicated to the blog archive. However, I have encountered an issue. I want to implement a toggle functionality that allows visitors to easily navigate through posts on the same page without having to reload the entire page or be directed to individual post pages. Although similar questions have been asked before, none of the examples provided seem to work for me. I simply want a show/hide feature that displays the excerpt by default and, when clicked, expands to show the complete content. When clicked again, it should revert back to the excerpt. Despite trying various solutions from Stack Overflow, nothing seems to be working so I decided to start fresh with my original files. Currently, the script is not functioning as expected in the loop-custom file despite my attempts.

Below is the JavaScript code I have implemented:


$(function () {
    $('.mainContent').hide();
    $('a.read').click(function () {
        $(this).parent('.excerpt').slideUp('fast');
        $(this).closest('.post').find('.mainContent').slideDown('fast');
//       $('.mainContent').show();
        return false;
    });
    $('a.read-less').click(function () {
        $(this).parent('.mainContent').slideUp('fast');
        $(this).closest('.post').find('.excerpt').slideDown('fast');
        return false;
    });
});

Here is the index file snippet:


<div id="content">

<div id="inner-content" class="row">

    <main id="main" class="large-8 medium-8 columns" role="main">           

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

            <!-- Additional archive styles can be found in the /parts directory -->
            <?php get_template_part( 'parts/loop', 'custom' ); ?>

        <?php endwhile; ?>  

            <?php joints_page_navi(); ?>

        <?php else : ?>

            <?php get_template_part( 'parts/content', 'missing' ); ?>

        <?php endif; ?>

    </main> <!-- end #main -->

    <?php get_sidebar(); ?>

</div> <!-- end #inner-content -->

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

Lastly, this is how the loop-custom file looks like:


<article class="post" id="post-<?php the_ID(); ?>" <?php post_class(''); ?> role="article">                 
<header class="article-header">
    <?php get_template_part( 'parts/content', 'byline' ); ?>
    <h2><?php the_title(); ?></h2>

</header> <!-- end article header -->

<section class="entry-content" itemprop="articleBody">
    <a href="<?php the_permalink() ?>"><?php the_post_thumbnail('full'); ?></a>


    <?php the_excerpt('<button class="tiny">' . __( 'Show more...', 'jointswp' ) . '</button>'); ?>
</section> <!-- end article section -->

Answer №1

UPDATE: Answer has been revised following testing on JSFiddle.

<div class="post-wrap">
    <h2>The Title</h2>
    <div class="post">
        <div class="excerpt">
            Insert brief excerpt here
        </div>
        <div class="whole-post">
            Slidey read more content should be placed here
        </div>
        <a href="#" class="read">Read More</a>
    </div>
</div>


.whole-post {
  display: none;
}

.post {
  position: relative;
  padding-bottom: 50px;
}

a.read {
  position: absolute;
  bottom: 10px;
  right: 10px;
}



$('a.read').click(function () {
     $(this).siblings('.excerpt').slideToggle(500);
     $(this).siblings('.whole-post').slideToggle(500);
});

Additional query inquiring about modifying the text of the "read more" button upon clicking - entails an extra line of jQuery, illustrated below:

  $('a.read').click(function () {
      $(this).siblings('.whole-post').is(':visible') ? $(this).html('Read More') : $(this).html('Read Less');
      $(this).siblings('.excerpt').slideToggle(500);
      $(this).siblings('.whole-post').slideToggle(500); 
  });

Find JSFiddle demonstration here.

Please note: The ternary syntax query ? truthy : falsey ; is shorthand for

if (query) { truthy } else { falsey } ;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with the execution of Javascript code. Edit required

After creating a registration form that allows users to input their information for registration, I encountered an issue where if certain fields were left empty or if the user name was unavailable or the email address was already registered, a warning mess ...

What is the method for asynchronously loading a javascript file that includes an ajax call?

Within my JavaScript file named JScript.js, there is a function that includes an AJAX call to a dot-net page. alert('jscript.js called'); function AddTag() { var htag = document.getElementById("hdntag").value.split('|'); var texttag = ...

Using a datepicker to calculate dates within a computed function in Vue

I'm currently exploring the most efficient method to dynamically generate fields based on date count or display a default option. Currently, I have successfully implemented the default setting of 11 days. However, my goal is to calculate the differen ...

The ng-click function ceases to trigger after the $location dependency is included in the controller

I need some help with running a ng-click function from my controller. The strange thing is, when I don't use the $location dependency, the ng-click function works fine. But as soon as I add $location to the controller, the ng-click function stops work ...

Reduce the size of the header in the Sydney theme for WordPress as you scroll

Currently, I am attempting to reduce the size of the header once scrolling down. My focus is on refining the child theme. Displayed below is a screenshot illustrating the appearance of the header at the top of the page: https://i.stack.imgur.com/wojGf.pn ...

Attempting to extract the text within a table row cell by clicking on the cell directly following it

I am trying to extract the data from a table row when I click on a specific div within that row HTML: <td class="ms-cellstyle ms-vb2">10</td> <td class="ms-cellstyle ms-vb2"> <div class="ms-chkmark-container"> <div ...

Attempting to display a collection of 16 diverse images by utilizing the Math.random function in conjunction with a

I have been attempting to retrieve 16 random images, but I keep getting duplicates. I am aware that a modification needs to be made to the one => one.number filter, however all attempts so far have been unsuccessful. import React from "react"; import ...

Tips for creating a zoomable drawing

I have been working on this javascript and html code but need some assistance in making the rectangle zoomable using mousewheel. Could someone provide guidance? var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var width ...

Next JS is successfully importing external scripts, however, it is failing to run them as

In my upcoming project using the latest version 12.1.6, I am incorporating bootstrap for enhanced design elements. The bootstrap CSS and JS files have been included from a CDN in the pages/_app.js file as shown below: import '../styles/globals.css&apo ...

What is the method for nesting data within a component's child>child>child structure?

In the structure I am working with, there is a hierarchy: Root component buttons (menu search component) - an input field for searching Widgets (widget component ) (Cats widget) - displays what is input in the menu search here. My challen ...

`Moving smoothly with a slider and then reversing direction`

I have implemented a range slider to control the value in an input field. The values can vary greatly, so I needed finer control for lower numbers that gradually expands for larger numbers. To address this issue, I utilized an easing equation based on the ...

Experiencing difficulties with arrays in JavaScript while using React Native

Programming Challenge let allURL = [] const [toReadURL, setToReadURL] = useState([]) useEffect(() => { const listReference = sReference(storage, parameterKey) // Retrieve all the prefixes and items. listAll(listReference) .then((res ...

Generating and Retrieving Dynamic URL with Jquery

My web page named single-colur.html has the ability to handle various query strings, such as: single-colour.html?id=1 single-colour.html?id=2 single-colour.html?id=3 single-colour.html?id=4 The parameter id in the URL corresponds to an entry in a table c ...

Utilize the key as the value for options within an object iteration in Vue.js

I have an object called colors, which stores color names: { "RD": "Red", "BL": "Blue", "GR": "Green", "YW": "Yellow" } In my dropdown menu, I'm generating options for each color in the colors object: <select v-model="colors"> <op ...

javascript creating a module to extend a nested object

Currently, I am working on a JavaScript module that includes an object of default options. Here is a snippet of the code: var myModule = function() { // Define option defaults var defaults = { foo: 'bar', fooObject: { option1 ...

Having trouble showing the fa-folders icon in Vuetify?

Utilizing both Vuetify and font-awesome icons has been a successful combination for my project. However, I am facing an issue where the 'fa-folders' icon is not displaying as expected: In the .ts file: import { library } from '@fortawesome/ ...

What is the best way to implement a delay before calling the owlCarousel function?

Is there a way to delay calling the owlCarousel function for 5 seconds? I attempted the following: $(document).ready(function(){ setInterval(function(){ $(".demo-slide").owlCarousel(); },5000); }); However, I encountered ...

Executing JavaScript code within an AJAX request

Having a problem with an AJAX function that I need help solving: PAGE A represents the main page. PAGE X represents the content loaded via AJAX. RES A represents the results from PAGE A. RES B represents the new results loaded via AJAX. PAGE A initially ...

Mac OS reports an Illegal instruction: 4 error when running NodeJS

Each time I try to execute my program, it gives me an Illegal instruction: 4 error without any clue as to why. The code snippet in question: glob('/path/music/*.mp3', function(error, files) { for(var i = 0; i < files.length; i++) { songs ...

Show values in an angular template using an array

I want to showcase values of an array using *ngFor const blockData = [ {text: sampleText1, array: [val1]}, {text: sampleText2, array: [val2, dat2]}, {text: sampleText3, array: [val3, dat3]} ] <div *ngFor="let data of blockData"> ...