How to smoothly open and close the standard details block (memo)

PubDate:

/ ModDate:

WordPress Customize Ideas | Personal WP Customization Notes (PWCN)

<Description based on the Act on Premiums and Representations> The content on this site may include product promotions.

Do you know about the “details block” in WordPress? Many people may not even notice it because it is hidden away in many blocks.

Using this block, you can easily create open/close content (so-called accordion content) that opens and closes when you click on the title. What’s more, you can freely include any number of blocks and specify colors, etc., so you can easily implement things that were previously implemented using shortcodes or plugins/themes with special blocks.

However, this “detail block” has some drawbacks. That’s what makes opening and closing go smoothly. It’s not possible to open slowly when you click, and then close slowly when you click again.

Well, it might still be better than using plugins for opening and closing content, but I’d like to achieve slowness if possible! After some trial and error, I was able to implement it, so I’m posting it here as a memo.

Perhaps those who have arrived at this page have been thinking the same thing and have been frustrated. .. I feel that this is the case, so I will leave the detailed explanation behind and show you a working sample below.

When you click on the title of the “Details” block, the content created with multiple blocks inside will slowly open and close.)

Details block title

insert paragraph

Column 1Column 2Column 3
Table contentsTable contentsTable contents
Table contentsTable contentsTable contents
Table contentsTable contentsTable contents
How to smoothly open and close the standard details block (memo)|Personal WP Customization Notes (PWCN)

What do you think? Oh, it feels nice. .. If you feel this way, please try implementing it.

I’m planning to continue implementing this method on my site, so I think it’s working fine as of , but I might change it if there’s a better method in the future. It doesn’t work, and it may have stopped working, so don’t worry. ..

Code to slowly open and close the “Details” block

It will work if you create a js file, insert the code below, and have it loaded after the WordPress standard jQuery (people who want to customize this kind of thing should be able to implement it with this level of explanation…).

/*** Slowly open and close standard details block ***/
/* Wrap the area from behind the /summary tag to before the /details tag in a div */
document.addEventListener("DOMContentLoaded", function() {
  // Get summary element
  var summaries = document.querySelectorAll("summary");

  // Perform processing on each summary element
  summaries.forEach(function(summary) {
    // Get details element
    var details = summary.parentNode;

    // Get the summary element and its sibling elements within the details element
    var elementsToWrap = [];
    var currentElement = summary.nextElementSibling;
    while (currentElement && currentElement.tagName !== "DETAILS") {
      elementsToWrap.push(currentElement);
      currentElement = currentElement.nextElementSibling;
    }

    // Wrap the element in a div
    var wrapper = document.createElement("div");
    elementsToWrap.forEach(function(element) {
      wrapper.appendChild(element);
    });

    // Assign class to div element
    wrapper.classList.add("pwcn-accordion__content"); // Please specify class name here

    // Insert the div element at the correct position within the details element
    details.insertBefore(wrapper, summary.nextSibling);
  });
});

/* Assign a class to each details summary tag */
jQuery(function () {
  jQuery('details').addClass('pwcn-accordion');
  jQuery('summary').addClass('pwcn-accordion__title');
});

/* Open and close slowly with a click */
jQuery(function($) {
    let accordionDetails = '.pwcn-accordion';
    let accordionSummary = '.pwcn-accordion__title';
    let accordionContent = '.pwcn-accordion__content';
    let speed = 400;

    $(accordionSummary).each(function (){
        $(this).on("click",function (event){
            event.preventDefault();
            let content = $(this).nextAll(accordionContent);
            if($(this).parent(accordionDetails).attr("open")){
                content.css('max-height', content.height()).animate({ 'max-height': 0 }, speed, function(){
                    $(this).parent(accordionDetails).removeAttr("open");
                    $(this).hide().css('max-height', '');
                });
            }else{
                $(this).parent(accordionDetails).attr("open","true");
                content.css('max-height', 0).show().animate({ 'max-height': content.prop('scrollHeight') }, speed, function(){
                    $(this).css('max-height', '');
                });
            }
        })
    });
});

What the code is doing

If you want to use jQuery in the details tag to smoothly open and close without using blocks, it is common to create an html structure like the one below and have jQuery process it according to opening and closing.

<details class="The class that wraps the whole thing">
  <summary class="title class">Title</summary>
  <div class="Class of contents to be opened and closed">
  .....
  </div>
</details>

I’ll omit jQuery, but it works like this.

  • Display the contents of the summary tag
  • When you click the summary tag with “title class” added, add the “open” attribute to the details tag.
  • Display the contents of the div tag only while the open attribute is attached

To achieve this, you will need to take the following steps in the standard WordPress details block.

  1. Add “class that wraps the whole” to the details tag
  2. Add “title class” to the summary tag
  3. Surround all contents, which may be multiple, with a div tag that has a “class of contents to be opened/closed”

The part that performs 1 and 2 in all the code above is the part below, which can be easily added with addClass.

/* Assign a class to each details summary tag */
jQuery(function () {
  jQuery('details').addClass('pwcn-accordion');
  jQuery('summary').addClass('pwcn-accordion__title');
});

The part that I struggled with was wrapping the contents to be opened and closed in a div. Well, it would be a good idea to manually group all the contents in the block editor and give them a “class for opening/closing contents”, but I would like to automate it if possible, and the following is what I came up with. The measure is to search for it and surround it with a div.

/* Wrap the area from behind the /summary tag to before the /details tag in a div */
document.addEventListener("DOMContentLoaded", function() {
  // Get summary element
  var summaries = document.querySelectorAll("summary");

  // Perform processing on each summary element
  summaries.forEach(function(summary) {
    // Get details element
    var details = summary.parentNode;

    // Get the summary element and its sibling elements within the details element
    var elementsToWrap = [];
    var currentElement = summary.nextElementSibling;
    while (currentElement && currentElement.tagName !== "DETAILS") {
      elementsToWrap.push(currentElement);
      currentElement = currentElement.nextElementSibling;
    }

    // Wrap the element in a div
    var wrapper = document.createElement("div");
    elementsToWrap.forEach(function(element) {
      wrapper.appendChild(element);
    });

    // Assign class to div element
    wrapper.classList.add("pwcn-accordion__content"); // Please specify class name here

    // Insert the div element at the correct position within the details element
    details.insertBefore(wrapper, summary.nextSibling);
  });
});

Finally, if you want to make the opening/closing speed a little faster (slower), change the number 400 in the section below.

    let speed = 400;

See below. .. Actually, I didn’t create this code all by myself, but I implemented a lot of animation information for many details tags introduced on the Internet, and after understanding the code to a certain extent, I started talking with AI. This is what I created. I feel the value of AI when I am able to accomplish something that I have wanted to do for many years but have not been able to do.

Precautions when using the code

This specification applies to all places where the details tag is used on the front end.

This code finds the part where the details tag is used in the HTML element output to the front end and performs the same operation.

Therefore, if you implement this code as is, all detail blocks (elements enclosed in details tags) on the page will have this behavior specification.

In the code, all that is done is adding a class and surrounding the contents with a div, so if the added CSS class does not overlap, it probably won’t conflict with what is output by other plugins. However, if there is a problem, you may need to take the following actions.

  • Set a switch in the right place, such as determining whether to enable jQuery (the above code) for each post.
  • Create a block style and switch whether it opens and closes smoothly (changes the way the whole thing is wrapped)

It is not reflected on the block editor side.

As mentioned above, this code is what is output to the front end. .. Since this is a conditional code, it will not be reflected on the post editing screen (block editor side).

If you’re looking for 100% compatibility between the editor and the front, you’ll probably have to work it out yourself, but I think it’s probably difficult to maintain 100% consistency no matter what theme you use. Personally, I think it can be considered as a specification.

Also, how to change the △ mark

How to change “▼” and “▲” marks

Although it has nothing to do with the purpose of this page, I would like to share a memo on how to change the “▼” mark that appears at the beginning of the button.

By doing the following, you can change the after element (after the opening/closing string) to display “[▽ Click to open]” and “[△ Click to close]”.

If you edit the “content” element in the site’s CSS code, it may not be applied properly, so if you change it on the developer tools and paste it, the text changes will often work.

details>summary {
  list-style-type: none;
  outline: none;
  cursor: pointer;
}

details>summary::-webkit-details-marker {
  display: none;
}

details>summary::after {
    content: '[▽ Click to open]';
}

details[open]>summary::after {
    content: '[△ Click to close]';
}

details[open]>summary {
  margin-bottom: 0.5rem;
}

Customization content for the details tag (block) on this site

Now that I have introduced the changes to the mark, I would like to finally show you the customizations that are currently being made to the details block on this site .

  • The opening/closing mechanism itself is made to open and close smoothly using jQuery on this page.
  • I am adding the style code to change as below
    • Change mark (displayed with unique icon)
    • Basic margin settings (title 12px, content 4px margin)
    • Opened content is white (site background color) regardless of block settings

Below is the style code added.

summary.pwcn-accordion__title {
	padding: 12px;
}

.pwcn-accordion__content {
	padding: 4px;
	background:#fff;
	margin-top:0;
}

details>summary {
	list-style-type: none;
	outline: none;
	cursor: pointer;
}

details>summary::-webkit-details-marker {
	display: none;
}

details>summary::before {
	content: '\eabe';
	font-family: 'hauicon';
	font-size: 1.5rem;
	vertical-align: sub;
	margin-right: 4px;
}

details[open]>summary::before {
	content: '\eabc';
	font-family: 'hauicon';
	font-size: 1.5rem;
	vertical-align: sub;
	margin-right: 4px;
}

This page is an English translation of the Japanese page. The information on the Japanese page may be more accurate because we maintain the Japanese page as the basis and not all content matches.
You can view the Japanese page by clicking the “View Japanese Page” button on the top right of the page, so please take a look.

If you found the content posted on this page or the reference code introduced helpful, please leave a comment in the comment section at the end of the page, or spread the word on SNS etc.

The methods and codes posted on this page have been confirmed to work in my environment as of the last update date. Please note that in principle, we will not respond even if we receive information about malfunctions or detailed customization methods in the comments section.

Until the end Thank you for reading.

The copyright and ownership of all content published on this page, including texts, images, and codes, belongs to this site, and reproduction is strictly prohibited.