Hide/show content starting in the middle of a paragraph

I need to be able to hide/show arbitrary content (paragraphs, lists, maybe pictures) based on a user clicking a link. This is easy enough, but I am running into a lot of problems trying to add this in the middle of a paragraph.

We’re trying to have a “read more” type link on certain sections of the page. It needs to be able to start anywhere in a paragraph of text. I tried this with a <span> tag but it caused problems because the span of content to hide may have to contain multiple paragraphs, lists, etc, so WordPress closed the span at the end of the first paragraph in order to make it valid HTML, which makes sense.

Next I tried adding a <div> tag, then inlined the div in my stylesheet, but WordPress closed the paragraph right before I add the div text, which also makes sense as valid HTML.

Does anyone have a recommendation on how to do this? I’d rather not remove WordPress’s natural addition of <p> tags because I anticipate that people who will be updating the site won’t be wanting to go in to the code view and add paragraph tags.

The HTML I’m using is:

<strong>What is community acupuncture?</strong> Here is the text that will show 
before the hidden section<div class="hidden-text"> Here is the rest of the paragraph 
in the hidden section.</p>

<p>Here is another paragraph of text that needs to be hidden. I realize that it is 
not valid HTML to have a div tag start in the middle of one paragraph and then encase 
a couple more paragraphs or a list or whathaveyou, which is why I am wondering how 
anyone else handled this issue.</p></div>

I have this as my css:

.hidden-text {
    display: inline;
}

and the little jquery I have so far is as follows:

$('.hidden-text').before("...").hide().after("<a href="#" class="hidden-text-toggle">Read More</a>");

I’m not sure if it’s better for me to post this here, as the problem is related directly to the <p> tags being added, or if it’d be better to post it in a front end design section of the site.

1
1

The problem with what you’re trying to do is that you split a block type html element <p>. In your example you effectively have <p><div></p></div>, which is simply no good. So you cannot mix <p> and <div> in this way. You can, however use a combination of paragraphs and classes:

<p>Text</p><p class="hide-from-here">More text</p>

Where it might be handy to expand </p><p class="hide-from-here"> from a shortcode. You could also generate your link with the same shortcode. You can make sure the paragraph with the hide-from-here class behaves as if it isn’t there using css.

Now you still need to hide the remaining paragraphs. Here jquery’s .nextAll comes in handy to give all remaining paragraphs the class

$("p:hide-from-here").nextAll().addClass( "following-paragraphs" );

On this class you define display:hidden, which you toggle with the link (or you remove the class).

Leave a Comment