1

I'm trying to assign background colors with JQuery using LESS variables.

The problem does come from using LESS variable because using RGB or hex values works like a charm.

Can we ask LESS to recompile from JQuery or something...?

I am compiling LESS client-side at the moment, for the time of production at least.

$(document).ready(function() {

    $('button:first-of-type').on('click', function() {
        
        // What I can do:
        $("main").css("background-color", 'rgb(154, 155, 234)');
    
        // What I want to do:
        $("main").css("background-color", "@bgColor1");

     }) 

     $('button:nth-of-type(2)').on('click', function() {
        
        // What I can do:
        $("main").css("background-color", "rgb(209, 255, 155)");
        
        // What I want to do:
        $("main").css("background-color", "@bgColor2");
        
     }) 
    
});
// Using LESS here

@bgColor1 : rgb(154, 155, 234);
@bgColor2 : rgb(209, 255, 155);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hello friend.</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<link rel="stylesheet/less" type="text/css" href="css/account.less"/>
    <script src="js/less/less.min.js"></script>
    <script src="js/account.js"></script>

</head>
    <body>

        <main>
         
              <button id="btnUpdatePublicName"> color 1 </button>
                    
              <button id="btnChangePassword" type="button"> color 2 </button>
                    
        </main>
    </body>
</html>

2 Answers 2

2

I too would love this functionality! The problem is that your LESS code is compiled into CSS, which doesn't have any concept of variables. The easiest solution is to create classes for each of your colors:

.bgColor1{
   background-color: @bgColor1
}

And then add this class using JQuery:

$("main").addClass("bgColor1");
Sign up to request clarification or add additional context in comments.

Comments

0

Another answer which merits consideration is using a plugin like sass extract (not sure if this applies given you are using less). This would extract variables at compile-type in a structured way.

If you are going to need these variables a lot, it might be work looking into, but would not be as straightforward as just creating classes (like I suggested earlier).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.