0

I have a page with the following select box on it:

    <form>
    <select id="themelist">
        <option value="style.less">Style 1</option>
        <option value="style-2.less">Style 2</option>
    </select>
    </form>

and this in the head:

<link rel="stylesheet/less" type="text/css" href="style.less" id="lesslink">
<script src="https://cdnjs.cloudflare.com/ajax/libs/less.js/3.7.1/less.min.js"></script>

I also have the following in my script.js:

    $("#themelist").change(function() {
    var newTheme = $("#themelist option:selected").val()
    $("#lesslink").attr({href : newTheme}); 
});

When I choose Style 2 from the dropdown, I get no errors, but it doesn't switch the style of the page. I know I'm getting into the function, and that newTheme is the right value, via alerts.

What am I missing here?

Thanks,

EDIT: After further review, it seems that going from style to style-2 enacts a few small CSS changes that are consistent, but random, and going from style-2 to style does nothing. Which now totally confuses me. This is also with using less.refresh(). Also, no errors are thrown in the console.

Reverend Bubbles
  • 1,363
  • 5
  • 15
  • 29
  • 1
    Duplicate of [Load less.js rules dynamically](https://stackoverflow.com/questions/3175013/load-less-js-rules-dynamically) – seven-phases-max Nov 20 '18 at 13:32
  • Not really. That question deals with how to refresh LESS when I edit the code. This question is about how to load in a brand new LESS file based on a dropdown selection. I've also tried refresh() and refreshStyles() already and neither does the trick. – Reverend Bubbles Nov 20 '18 at 14:49

1 Answers1

0

I found the answer in another question on SO, but I finally searched a different way and found it.

jQuery and LESS, stylesheet update only works once

had the answer, which was the following:

This is due to the way LESS seems to work. It parses the less file, and then adds a style attribute to the DOM. In practice, these seem to follow the format of the following

<style type='text/css' id='less:<<NAME OF YOUR LESS FILE>>'>
   /*your parsed content*/
</style>

The reason it's not loading properly is because LESS is parsing the content, finding the existing style block, and not adding it. Subsequent style blocks are being added at the end of head so I was getting the 'last in' version of the style.

Once I changed the function to include the following:

$('style[id^="less:"]').remove();

before I reset the href, it worked perfectly!

To be clear, the question was different, but the answer to that question also happened to be the answer to this question in that LESS was adding its own bit of code to the end of the head that was screwing with me.

Liam
  • 27,717
  • 28
  • 128
  • 190
Reverend Bubbles
  • 1,363
  • 5
  • 15
  • 29
  • BAH!! This was working, and now, this morning, it suddenly doesn't remove the inserted style block anymore. I'm back to square one. :( – Reverend Bubbles Nov 27 '18 at 15:05