0

I'm using a show/hide plugin that has shortcode with a parameter with state="open" or state = "closed" I would like to have it open on desktop but closed on mobile. Is it possible to change this parameter based on a media query or maybe some javascript or something that only inserts the shortcode if the screen size is less than 768px?

  • What does the parameter actually change in the output? – Jacob Peattie Feb 5 at 12:25
-1

Edit: the reason I'm suggesting Javascript, is that PHP and your webserver, and thus WordPress, don't know really anything about the client or it's screensize. You may be able to tell that someone is using Chrome or Safari, but you have no way of knowing their browser's dimensions until you can interact with Javascript.

If you shortcode's resulting content has a unique ID or a CSS class you can target, you could add some simple Javascript to your page. Supposing your shortcode outputs something like:

<div class="my-shortcode-thing">
    <!-- HTML here -->
</div>
// Using jQuery
jQuery( function($) {
    if ( 768 <= parseInt( $(window).width(), 10 ) ) {
        return;
    }

    $('.my-shortcode-thing').remove();
} );

I can provide an example in "vanilla" Javascript as well if needed.

The downside here is that it won't act as a "true" mediaquery, where resizing the browser will make it appear/disappear dynamically, but it's not impossible. If just hiding/displaying the content is good enough (i.e. you don't need to remove it, just hide it), you could do something like:

jQuery( function($) {
    // Will store our setTimeout result
    var timeout = null;

    // Whether we're displaying the things.
    var displaying = true;

    function maybeToggleContent() {
        // Use your content's selector here
        var things = $('.my-shortcode-thing');

        if ( 768 <= parseInt( $(window).width(), 10 ) ) {
            if ( displaying ) {
                return;
            }

            displaying = true;
            things.show(); // or things.fadeIn() for "fancy" stuff
            return;
        }

        if ( ! displaying ) {
            return;
        }

        displaying = false;
        things.hide(); // Again, .fadeOut() for extra pizazz
    }

    $(window).on('resize', function() {
        // Using a timeout here so we don't bog down the resize event.
        clearTimeout(timeout);
        timeout = setTimeout( maybeToggleContent, 500);
     } );

} );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.