🐘

JQuery

19 notes  •  PHP & Web Dev

WordPress Excerpt Function in jQuery

This guide shows how to create a custom "Read More" excerpt toggle in WordPress using a shortcode in functions.php and a jQuery fade animation.

Prerequisites

  • Access to your theme's functions.php and a custom JavaScript file (e.g. via a child theme or plugin)
  • jQuery loaded on the page

Step 1: Register the Shortcode in functions.php

Add the following shortcode handler to your theme's functions.php:

function display_excerpt_function($atts, $content = null) {
    return '<a id="EndExcerpt" href="#">Read More</a>'
         . '<span id="hidden-content">' . $content . '</span>';
}
add_shortcode('hide-content', 'display_excerpt_function');

Step 2: Add the jQuery Toggle Script

Enqueue or paste the following in your custom JS file:

jQuery("#hidden-content, #HideExcerpt").hide();

jQuery("#EndExcerpt, #HideExcerpt").click(function() {
    jQuery("#EndExcerpt, #HideExcerpt").fadeToggle();
    jQuery("#hidden-content").fadeToggle("slow", "linear");
    return false;
});

Step 3: Style the Read More Button

#EndExcerpt {
    float: right;
    padding: 4px 20px;
    text-align: right;
    background-color: rgb(51, 51, 51);
    color: white;
    margin-top: 15px;
}

Usage

Wrap hidden content in the shortcode inside any post or page:

[hide-content]This text is hidden until the user clicks Read More.[/hide-content]

Notes

  • The #HideExcerpt element is optional — add it to the shortcode output if you want a visible "Hide" button after expansion.
  • Use fadeToggle() instead of toggle() for a smoother UX.

Smooth Animated Scrolling for Same-Page Links with jQuery

This guide explains how to implement smooth animated scrolling for same-page anchor links using jQuery, with proper guards against false positives and inline handler conflicts.

Prerequisites

  • jQuery 1.2 or later loaded on the page

Basic Implementation

The initial approach attaches a click handler to all links containing # in the href, then scrolls to the target element:

$(document).ready(function() {
    $('a[href*=#]').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
            && location.hostname == this.hostname) {

            var $target = $(this.hash);
            $target = $target.length && $target
                      || $('[name=' + this.hash.slice(1) + ']');

            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html, body').animate({ scrollTop: targetOffset }, 1000);
                return false;
            }
        }
    });
});

Improved Version: Guard Against Edge Cases

The improved version uses .each() to iterate links first and binds the click handler only to valid same-page anchors. This avoids hijacking links with bare # hrefs and prevents conflicts with inline onclick handlers.

$(document).ready(function() {
    $('a[href*=#]').each(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
            && location.hostname == this.hostname
            && this.hash.replace(/#/, '')) {

            var $targetId     = $(this.hash);
            var $targetAnchor = $('[name=' + this.hash.slice(1) + ']');
            var $target       = $targetId.length     ? $targetId
                              : $targetAnchor.length ? $targetAnchor
                              : false;

            if ($target) {
                var targetOffset = $target.offset().top;
                $(this).click(function() {
                    $('html, body').animate({ scrollTop: targetOffset }, 400);
                    return false;
                });
            }
        }
    });
});

Notes

  • The pathname and hostname checks ensure only links pointing to the current page trigger the animation — fully-qualified, relative, and fragment-only URLs are all handled.
  • The this.hash.replace(/#/, '') guard prevents a bare # href from causing a false match in Safari.
  • Binding inside .each() (loop-first, bind-last) prevents the animation from interfering with links that have existing onclick handlers.
  • Adjust the duration value (400 ms above) to control scroll speed.

Show a Popup When a Menu Item is Clicked with jQuery

This guide shows how to trigger a Ninja Popups overlay by clicking a specific WordPress menu item, using jQuery to control visibility.

Prerequisites

  • Ninja Popups plugin installed and a popup created (note its ID, e.g. 398)
  • The menu item's ID (find it via browser inspector, e.g. menu-item-417)
  • jQuery loaded on the page

Step 1: Hide the Popup with CSS

Ninja Popups normally auto-shows on load. Override that with CSS to keep it hidden until triggered:

.snp-pop-398-overlay,
.snp-pop-398-wrap {
    visibility: hidden;
}

Step 2: Show the Popup on Menu Click

jQuery("#menu-item-417").click(function() {
    jQuery(".snp-pop-398-overlay").css('visibility', 'visible');
    jQuery(".snp-pop-398-wrap").css('visibility', 'visible');
});

Notes

  • Replace 398 with your actual popup ID and 417 with the menu item's ID.
  • To close the popup, add a click handler on the overlay that sets visibility back to hidden.
  • This approach works only with Ninja Popups; other popup plugins use different class naming conventions.

Check if a Checkbox is Checked and Alert with jQuery

This guide shows how to use jQuery to detect when a checkbox is unchecked and display an alert, then force it back to a checked state — useful for enforcing terms-and-conditions acceptance.

Prerequisites

  • jQuery loaded on the page
  • A checkbox input with the target name attribute

Implementation

$("input[name='checkboxesc20']").click(function() {
    if ($(this).prop("checked") == true) {
        // Checkbox is checked — proceed normally
    } else if ($(this).prop("checked") == false) {
        alert("You must agree to our T&C and Privacy Policy.");
        // Force the checkbox back to checked
        $("input[name='checkboxesc20']").prop('checked', true);
    }
});

Notes

  • Replace checkboxesc20 with your checkbox's actual name attribute value.
  • Re-checking the box after the alert prevents the user from accidentally leaving it unchecked.
  • For form-level validation (on submit rather than on click), move the check into a $('form').submit() handler and call e.preventDefault() to block submission.

Trigger an Alert on Button Click with jQuery

This guide demonstrates how to attach a click handler to a button and display an alert message using jQuery.

Prerequisites

  • jQuery loaded on the page
  • A button element with an id attribute

Implementation

$("#fcbutton").click(function() {
    alert("Your message.");
});

Notes

  • Replace fcbutton with your button's actual id.
  • Wrap this in a $(document).ready() handler if the script loads before the DOM is ready.
  • For better UX, consider replacing alert() with a custom modal or inline notification instead of a browser dialog.

Get Selected Option Value with jQuery

This guide shows how to read the currently selected value from a <select> dropdown and display it in an input field using jQuery.

Prerequisites

  • jQuery loaded on the page
  • A <select> element and a text input to display the result

HTML Structure

<select id="dropdown_selector">
    <option value="val1">Option 1</option>
    <option value="val2">Option 2</option>
    <option value="val3">Option 3</option>
</select>

<input type="text" id="showoption" placeholder="Selected value appears here">

jQuery Script

$(document).ready(function() {
    // Bind change event to the select element
    $('#dropdown_selector').change(function() {
        // Get the currently selected option's value
        var option = $(this).find('option:selected').val();
        // Write it to the input field
        $('#showoption').val(option);
    });
});

Notes

  • Use .val() on the <select> directly as a shorthand: $(this).val() returns the selected value without needing .find('option:selected').
  • To get the visible text (not the value attribute), use $(this).find('option:selected').text().
  • To read the selected value on page load (before any change), trigger the event manually: $('#dropdown_selector').trigger('change');

Highlight Unchecked Checkboxes with jQuery

This guide shows how to visually highlight unchecked checkboxes when a submit button is clicked, using jQuery to add a CSS class to their parent elements.

Prerequisites

  • jQuery loaded on the page
  • Checkboxes with a shared class (e.g. new_order) and a submit button with id submit

HTML Structure

<ul>
    <li><input type="checkbox" class="new_order"> Item A</li>
    <li><input type="checkbox" class="new_order"> Item B</li>
</ul>
<button id="submit">Submit</button>

jQuery Script

$('#submit').click(function() {
    $('.new_order').each(function() {
        if ($(this).prop('checked') === false) {
            $(this).parent().addClass('incomplete');
        }
    });
});

CSS for the Highlight

.incomplete {
    border: 1px solid orange;
    background: yellow;
}

Notes

  • To target a specific ancestor rather than the direct parent, pass a selector to .parent(): $(this).parent('li').addClass('incomplete');
  • To remove the highlight once the user checks the box, add a change handler: $('.new_order').change(function() { $(this).parent().removeClass('incomplete'); });
  • Combine this with actual form validation to block submission when required checkboxes are unchecked.

Add or Change Text with jQuery

This guide covers two common text manipulation patterns with jQuery: inserting text adjacent to an element, and finding-and-replacing text inside elements matching a CSS class.

Prerequisites

  • jQuery loaded on the page

Insert Text After a Button

Add a legend or note immediately after a button that contains specific text:

// After the button labelled "Book now"
jQuery(":contains('Book now')").closest('button').after("Your legend text here");

// After the last submit button on the page
jQuery(":submit").last().after("Your legend text here");

Find and Replace Text Inside Elements

Use .text() with a callback to replace a substring inside all matching elements:

jQuery(document).ready(function($) {
    $(".plus-table__text-inner").text(function() {
        return $(this).text().replace(
            "Artisan Global Discovery Fund",
            "ECP Growth Companies Fund"
        );
    });

    $(".plus-table__text-inner").text(function() {
        return $(this).text().replace(
            "MSCI All Country World SMID Cap Net Index in AUD",
            "S&P/ASX 300 Accumulation Index"
        );
    });
});

Notes

  • The :contains() selector is case-sensitive.
  • .text() with a replacement callback strips HTML tags; use .html() if the content contains markup you want to preserve.
  • JavaScript's String.replace() only replaces the first match by default. To replace all occurrences use a global regex: .replace(/Old Text/g, 'New Text').

jQuery toggle() Method Examples

This guide demonstrates the jQuery toggle() method, which alternately shows and hides matched elements each time it is called.

Prerequisites

  • jQuery loaded on the page

Basic Toggle on Button Click

Toggle the visibility of all paragraph elements when a button is clicked, with a 500 ms animation:

$(document).ready(function() {
    $("button").click(function() {
        $("p").toggle(500);
    });
});

HTML Example

<button>Toggle Paragraphs</button>
<p>This is a paragraph with a little content.</p>
<p>This is another small paragraph.</p>

Notes

  • Passing a duration (in milliseconds) to toggle() applies a fade-like show/hide animation. Omit it for an instant toggle.
  • To toggle a specific element rather than all <p> tags, use an id or class selector: $("#myElement").toggle(500);
  • toggleClass() is the CSS-class equivalent — it adds the class if absent and removes it if present, which is preferable for pure visual state changes.

Set Parallax Section Background Dynamically with jQuery

This guide shows how to fix a Safari-specific issue where parallax section backgrounds fail to display, by detecting Safari via the user agent and overriding the background-attachment property with jQuery.

Prerequisites

  • jQuery loaded on the page
  • A parallax section with a known CSS class (e.g. section.bzcus)
  • Code placed in footer.php (or equivalent) so it runs after the section is in the DOM

Implementation

jQuery(document).ready(function($) {
    // Detect Safari (excluding Chrome on iOS which also uses Apple vendor)
    var isSafari = navigator.vendor
        && navigator.vendor.indexOf('Apple') > -1
        && navigator.userAgent
        && !navigator.userAgent.match('CriOS');

    if (isSafari) {
        // Safari does not support background-attachment: fixed on elements
        // inside overflow:hidden containers — fall back to scroll
        $('section.bzcus').css('background-attachment', 'scroll');
    }
});

Notes

  • Safari ignores background-attachment: fixed on elements inside scrollable containers. Switching to scroll restores the background while losing the parallax effect only for Safari users.
  • The CriOS check excludes Chrome running on iOS (which reports Apple as vendor) so the fix only targets true Safari.
  • Place this script in footer.php or load it deferred so the section element exists in the DOM when the script runs.

Remove Anchor Tags Surrounding Images with jQuery

This guide shows how to use jQuery's .unwrap() method to remove anchor tags that wrap images — for example, when a CMS or page builder automatically links every gallery image but you want the images to be non-clickable.

Prerequisites

  • jQuery loaded on the page

Remove All Anchor Wrappers from Images

jQuery(document).ready(function($) {
    $('img').unwrap('a');
});

Remove Anchor Wrappers Only Within a Container

jQuery(document).ready(function($) {
    $('.gallery img').unwrap('a');
});

Alternative: Prevent Clicks Without Removing the Anchor

jQuery(document).ready(function($) {
    $('.gallery a').on('click', function(e) {
        e.preventDefault();
    });
});

Notes

  • .unwrap() removes the parent element of the selected elements. Passing a selector (e.g. 'a') limits removal to parents that match — preventing accidental removal of other wrapper elements.
  • Use the scoped version ('.gallery img') rather than a bare 'img' selector to avoid affecting images elsewhere on the page.
  • If the lightbox or link is added by a plugin, disabling it in the plugin settings is preferable to overriding it with jQuery.

Hide a Specific Anchor Tag with jQuery

This guide demonstrates two techniques for handling specific anchor tags with jQuery: hiding the parent element of an anchor, and disabling the link's navigation without removing it from the DOM.

Prerequisites

  • jQuery loaded on the page

Technique 1: Hide the Parent Element of an Anchor

Select the anchor by its exact href value and hide its containing element:

jQuery(document).ready(function($) {
    $('a[href="https://example.com/our-people/consultant/"]').parent().hide();
});

Technique 2: Disable Navigation Without Hiding

Remove the href attribute so the anchor becomes a non-navigating element, while keeping it visible and styled as a pointer:

jQuery(document).ready(function($) {
    $("a[href='https://example.com/product-category/sunglasses/']")
        .removeAttr("href")
        .css("cursor", "pointer");
});

Notes

  • Use .parent() to hide the containing <li> or <div> if the anchor itself has no layout footprint (e.g. inside a menu).
  • .removeAttr("href") makes the element inert for navigation but preserves its text and appearance. This is preferable to display:none when you still want the element visible.
  • Target anchors by href only when the URL is stable. Class or ID-based selectors are more maintainable.

Replace Text Inside a CSS Class with jQuery

This guide covers two approaches to replacing text inside elements matched by a CSS class: swapping out full element content using .replaceWith(), and updating button or link text using .text().

Prerequisites

  • jQuery loaded on the page

Replace an Element's Content Entirely

Use .replaceWith() to substitute the entire matched element (including its tag) with new HTML:

jQuery(document).ready(function($) {
    $("div.phone-info").replaceWith(
        '<div class="phone-info">' +
        '123 Example Street, City, Country<br>' +
        'Ph: +1 555 123 4567' +
        '</div>'
    );
});

Replace Text Inside a Link or Button

Use .text() to change the visible label of all elements matching a class:

jQuery(document).ready(function($) {
    // Change "Read More" link text (class: more-link)
    jQuery(".more-link").text("Scopri di più");
});

Notes

  • .replaceWith() removes the original element from the DOM and inserts the replacement — all event handlers bound to the original element are lost.
  • .text(newValue) sets the text content of all matched elements. Use .html(newValue) if the replacement contains markup.
  • For internationalised sites, store replacement strings in a JS object rather than hard-coding them inline.

Add target="_blank" to Links in a Specific Class with jQuery

This guide shows how to use jQuery to set target="_blank" on all anchor tags that share a specific CSS class, causing them to open in a new browser tab.

Prerequisites

  • jQuery loaded on the page
  • Anchor elements with a known class (e.g. elementor-post__read-more)

Implementation

jQuery("a.elementor-post__read-more").attr('target', '_blank');

Wrap in a Document-Ready Handler (if needed)

jQuery(document).ready(function($) {
    $("a.elementor-post__read-more").attr('target', '_blank');
});

Notes

  • Replace elementor-post__read-more with the actual class on your anchor tags.
  • For security, always pair target="_blank" with rel="noopener noreferrer" to prevent the new tab from accessing the opener's window object: .attr({ target: '_blank', rel: 'noopener noreferrer' })
  • If the links are generated dynamically (e.g. via AJAX), run this snippet after the dynamic content is inserted, or use event delegation instead.

Disable href on Anchor Tags with jQuery

This guide covers three jQuery techniques for disabling anchor tag navigation — useful when you need to suppress links generated by a theme or plugin without editing template files directly.

Prerequisites

  • jQuery loaded on the page
  • Custom JS file enqueued (e.g. in wp-content/themes/yourtheme/js/custom.js)
  • All custom JS must be placed inside a $(document).ready() wrapper

Technique 1: preventDefault()

Intercepts the click event and stops navigation while keeping the href attribute intact:

$(document).ready(function() {
    $('a').click(function(e) {
        e.preventDefault();
    });
});

To target a specific link rather than all anchors:

$('a[href="https://example.com/page-to-disable"]').click(function(e) {
    e.preventDefault();
});

Technique 2: removeAttr("href")

Removes the href attribute entirely so the element is no longer a navigating link:

$(document).ready(function() {
    $('a.specific-class').removeAttr("href");
});

Technique 3: Return false from Click Handler

Returning false from a jQuery click handler is equivalent to calling both e.preventDefault() and e.stopPropagation():

$(document).ready(function() {
    $('a.specific-class').click(function() {
        return false;
    });
});

Notes

  • Use a precise CSS selector (id, class, or attribute) rather than a bare 'a' to avoid disabling unintended links across the site.
  • Technique 1 is the cleanest for accessibility — screen readers can still read the href value.
  • Technique 2 is the most aggressive — the element loses its link semantics entirely.
  • Use browser DevTools (F12 → Inspector) to find a selector specific to the link you want to disable.

Select Images from Server with jQuery (CKFinder/File Manager)

This guide shows a jQuery script that can be run in the browser console inside a file manager (such as CKFinder) to automatically select checkboxes for files that are not resized variants — i.e. original image files without dimension suffixes in their filenames.

Prerequisites

  • A file manager table rendered with class widefat (standard in WordPress media or CKFinder UI)
  • jQuery available in the page context

How It Works

The script iterates every table row, inspects cell text for the presence of x (which appears in dimension strings like 300x200), and checks the row's checkbox only when no dimension string is found — selecting originals and skipping thumbnails.

Script

jQuery('.widefat').find('tr').each(function() {
    var row = jQuery(this);

    if (row.find('input[type="checkbox"]')) {
        var columns = row.find('td:not(:first-child)');

        jQuery(columns).each(function(index) {
            var str = jQuery(this).text();

            // Skip rows with "x" in text (dimension strings like 300x200)
            // and skip the header "File" cell
            if (str.indexOf('x') === -1) {
                if (str !== "File") {
                    var checkboxid = row.find("input[type='checkbox']").prop("id");
                    if (checkboxid !== null) {
                        jQuery('#' + checkboxid).prop('checked', true);
                    }
                }
            }
        });
    }
});

Notes

  • This script uses a simple indexOf('x') heuristic to detect dimension strings. Extend it with a regex (e.g. /\d+x\d+/) for more precise matching: if (!/\d+x\d+/.test(str))
  • Run this in the browser DevTools console while the file manager table is visible.
  • The script does not submit or delete anything — it only toggles checkbox state. Always review the selection before confirming any bulk action.

Add Dynamic Title to a Contact Form with jQuery

This guide shows how to inject a dynamic job title into a contact form when a user clicks an "Apply" button, so the form always reflects the position the applicant is applying for.

Prerequisites

  • jQuery loaded on the page
  • A page builder layout where each job listing module (.et_pb_module) has a preceding sibling with an h3 heading containing the job title
  • A Contact Form 7 form with id wpcf7-f698-o1 embedded on the page
  • An "Apply" button with class applybutton inside each listing module

Implementation

jQuery(function($) {
    $('body').on('click', '.applybutton', function(e) {
        // Read the job title from the h3 in the preceding sibling module
        var job_title = $(this)
            .closest('.et_pb_module')
            .prev()
            .find('h3')
            .text();

        // Remove any previously injected title line
        $('.ha_job_title').remove();

        // Insert the job title after the first div inside the form
        $('#wpcf7-f698-o1 form div').first().after(
            '<p class="ha_job_title">You are applying for the job: <strong>'
            + job_title +
            '</strong></p>'
        );
    });
});

Notes

  • Event delegation ($('body').on('click', '.applybutton', ...)) is used so the handler works even if the buttons are rendered dynamically after page load.
  • The $('.ha_job_title').remove() call clears any previously injected title before inserting a fresh one — prevents duplicates if the user clicks multiple apply buttons.
  • Adjust the .closest() and .prev().find() traversal chain to match your actual page builder markup if it differs from Divi (.et_pb_module).
  • Replace the form selector #wpcf7-f698-o1 with your actual Contact Form 7 form's rendered ID.