Jeton R.
Jeton R.

Reputation: 395

Better way to add/remove class with jquery

I am using wordpress theme customizer to change color scheme of my theme but was wondering if there is any shorter way to achieve this from what i have below. Thank you.

wp.customize('orn_color_scheme',function( value ) {
    value.bind(function(to) {
    var $color;
    if($('body').hasClass('default')) { $color = 'default' }
    if($('body').hasClass('beige')) { $color = 'beige' }
    if($('body').hasClass('blue')) { $color = 'blue' }
    if($('body').hasClass('celadon')) { $color = 'celadon' }
    if($('body').hasClass('cherry')) { $color = 'cherry' }
    if($('body').hasClass('cyan')) { $color = 'cyan' }
    if($('body').hasClass('dark')) { $color = 'dark' }
    if($('body').hasClass('dirty-green')) { $color = 'green' }
    if($('body').hasClass('orchid')) { $color = 'orchid' }
    if($('body').hasClass('red')) { $color = 'red' }

    $('#orbitnews-color-scheme-css').attr('href', '<?php echo get_template_directory_uri(); ?>/layouts/colors/' + to + '.css');
    $('body').removeClass($color).addClass(to);
        });
    });

Upvotes: 1

Views: 381

Answers (3)

techMonster
techMonster

Reputation: 226

Maybe you can make use of data attribute to make the code shorter and adjustable:

HTML:

<body class="someclass1 someclass2 red" data-color="red"></body>

Javascript:

function(to) {
    var $color = $('body').data().color;

    $('#orbitnews-color-scheme-css').attr('href', '<?php echo get_template_directory_uri(); ?>/layouts/colors/' + to + '.css');

    $('body').removeClass($color).addClass(to).data("color",to);
}

Upvotes: 0

GautamD31
GautamD31

Reputation: 28763

Try like

$('body').toggleClass( color , to);

So it will be

wp.customize('orn_color_scheme',function( value ) {
     value.bind(function(to) {
         var color;
         color = $('body').attr('class');
         $('#orbitnews-color-scheme-css').attr('href', '<?php echo get_template_directory_uri(); ?>/layouts/colors/' + to + '.css');
         $('body').toggleClass( color , to);
     });
});

Upvotes: 0

adeneo
adeneo

Reputation: 318222

var colors = ['default', 
              'beige',
              'blue',
              'celadon',
              'cherry'
              ... etc
             ];

wp.customize('orn_color_scheme',function( value ) {
    value.bind(function(to) {
        var $color;
        $.each(colors, function(_, color)) {
            if ( $('body').hasClasss(color) ) {
                $color = color;
                break;
            }
        });
        $('#orbitnews-color-scheme-css').prop('href', '<?php echo get_template_directory_uri(); ?>/layouts/colors/' + to + '.css');
        $('body').removeClass($color).addClass(to);
    });
});

Upvotes: 1

Related Questions