Make Things Appear and Disappear without JQuery in MODX

Sometimes, you just want to hide some text until the user clicks on a something. You don’t want any fancy effects and you don’t really need JQuery. Maybe it’s a subsidiary form field that shouldn’t show up unless the user clicks on a checkbox, or maybe it’s just some “read more … ” text to be shown to interested readers.

You can do this quite easily with straight JavaScript. In fact you don’t even need any CSS for it. Here’s an example of a typical “Read More” effect.

The example above will show the additional material inline and hide the “Read More” line when the user clicks on “Read More.” It’s a one-way transform. Once the additional material is visible, the “Read More” link is gone, so there’s no way to hide the extra material without reloading the page. You could add a button that would toggle the additional text in and out, but we don’t really need that here.

Try It

This section has the code above without the tags that make it visible so you can see it in action:

Blah, blah, blah. Read More . . . This is the extra material to be hidden until the user clicks on the Read More button.

Form Example

Let’s look at another example that toggles the visibility of an extra form field when the user selects or deselects a checkbox. We’ve renamed the toggle function to toggle2 so it won’t conflict with the other example. In this case clicking on the “Send Test Email” checkbox reveals another input field to enter an email address. The revealed input field is indented a little to help the user see that it has been added.

The JavaScript

This code is very similar to the example above. It no longer toggles the trigger because we want the checkbox to remain visible at all times. This code is a true toggle, when the user clicks on the checkbox, it reverses the current state of the additional input field. Checking the box shows the additional field. Unchecking it hides the field. That’s why it’s important to have that field hidden by the style attribute when the form is first loaded. In this example, we’re also setting the display style to block instead of inline.

Try It

Here’s the same code in executable form:

Send Test Email?

Email Address for Test

Summing Up

Sometimes you want a fancy animated effect which fades in or slides in a particular direction. In that case, it’s hard to beat JQuery. At other times, though, you just want a quick way to hide and reveal bits of content. In those cases, it’s fairly simple to do the job with straight JavaScript and avoid the overhead of JQuery.