Support » Fixing WordPress » Customizer JS and addClass

  • I’m hoping someone can point me in the direction of a simple answer. Feels like I’m missing something obvious…

    When trying to use the Customizer JS API, I ran into a problem appending classes to an element. Because the Customizer postMessage message sends on keyup, typing a class into the form element sends messages:
    c
    cl
    cla
    class

    and so on.. The problem is: if I’m trying to add a class to the element by using the addClass function of jQuery, I get all four of those “classes” added to the element because they were each acted upon separately. Is there some way to prevent this?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Here is a little algorithm to remove the unnecessary classes from the element every time you type something into the form ^^ Use it inside the function you get the postMessage

    var class = to;
    
    for ( var i = class.length - 1; i > 0; i-- ) {
        var removeThisClass = class.substring(0,i);
        $('your_element_selector_here').removeClass(removeThisClass);
    }

    A working example would be:

    wp.customize( 'your_setting_id', function( value ) {
        value.bind( function( to ) {
    
            var class = to;
    
            $('your_element_selector_here').addClass(class);
    
            for ( var i = class.length - 1; i > 0; i-- ) {
                var removeThisClass = class.substring(0,i);
                $('your_element_selector_here').removeClass(removeThisClass);
            }
    
        } );
    });

    Cheers

    • This reply was modified 1 year, 7 months ago by ivchodev.
    • This reply was modified 1 year, 7 months ago by ivchodev.
    • This reply was modified 1 year, 7 months ago by ivchodev.

    Awesome, thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Customizer JS and addClass’ is closed to new replies.