oneday
oneday

Reputation: 1629

Changing classes of an element dynamically

I'm trying to create a version picker for my website. There are two options I would like to include - color picker and text align picker.

When a specific option is clicked, it's supposed to apply classes to the body that are later styled in CSS.

Here's the code for it:

HTML:

<div id="picker">
  <ul id="colors">
    <li id="version-6" class="choose-color">version 6</li>
    <li id="version-5" class="choose-color">version 5</li>
  </ul>
  <ul id="align">
    <li id="text-to-center" class="choose-align">text-center</li>
    <li id="text-to-left" class="choose-align">text-left</li>
  </ul>
</div>

JS:

$('.choose-color').on('click', function(){
    var switchTo = $(this).attr('id')
    var arrClasses = [];

    $('[class*="version-"]').removeClass(function () {
         console.log(this.className);
        var className = this.className.match(/version-\d+/);
        if (className) {
            arrClasses.push(className[0])
            return className[0];
        }
    }).addClass(switchTo);

});

$('.choose-align').on('click', function(){
    var switchTo2 = $(this).attr('id')
    var arrClasses2 = [];

    $('[class*="text-to-"]').removeClass(function () {
        var className2 = this.className.match(/text-to-\d+/);
        if (className2) {
            arrClasses2.push(className2[0])
            console.log(className2[0])
            return className2[0];
        }
    }).addClass(switchTo2);
});

The first piece of js code (color picker) works great - it deletes any class starting with "version-" and then adds the class equal to the ID of the element clicked.

I tried re-creating this behaviour with the second piece of code, but without success.

It's only adding the class, but not removing the previous one.

Is it a typo somewhere or is the whole idea wrong?

Upvotes: 0

Views: 48

Answers (1)

Kevin Jantzer
Kevin Jantzer

Reputation: 9451

Your problem is the regular expression in the second one:

var className2 = this.className.match(/text-to-\d+/);

\d matches a number. Change it to . (which matches any character)

Upvotes: 1

Related Questions