Warm tip: This article is reproduced from stackoverflow.com, please click
css if-statement javascript sharepoint vue.js

How can one use CSS in an if statement of JavaScript code?

发布于 2020-04-13 10:24:39

I have a Vue.js component and I want to use this CSS part when the if conditon is true:

<style type="text/css">  
 #sideNavBox {DISPLAY: none}  
 #contentBox {MARGIN-LEFT: 5px}  
</style> 

Here's the JavaScript:

IsCurrentUserMemberOfGroup("Admins", function (isCurrentUserInGroup) {
    if(isCurrentUserInGroup) {
        for (var i = 0; i < data.length; i++) {
            $this.teams.push({
                id: data[i].ID,
                TeamName: data[i].TeamName.TeamName,
                Coach: data[i].Coach,
                CoachTel: data[i].CoachTel,
                CoachAddress: data[i].CoachAddress,
                CoachAssistant: data[i].CoachAssistant,
                CoachAssistTel: data[i].CoachAssistTel,
                CoachAssistAddress: data[i].CoachAssistAddress,
                Email: data[i].Email
            });
        }
        console.log("Works!")
    }
});

I could add the CSS part in

<style>
</style>

but then it would be used all the time.

How can one use the CSS part if the if statement is true?

Questioner
Politics Student
Viewed
47
Jeremy Harris 2020-02-03 22:01

You have a couple options here:

  1. Dynamically apply a class to the element based on the condition
  2. Dynamically apply inline styling to the element based on the condition

Personally, I prefer to use classes. Here is an example:

const val = 42;

// Conditional
if (val === 42) {
   setTimeout(() => {
      document.querySelector('.box').classList.add('box--blue');
   }, 1000);
}

if (val === 100) {
   setTimeout(() => {
      document.querySelector('.box').classList.add('box--green');
   }, 1000);
}
.box {
   width: 100px;
   height: 100px;
   background-color: deeppink;
   transition: all 2s ease;
}

.box--blue {
   background-color: dodgerblue;
}

.box--green {
   background-color: limegreen;
}
<div class="box" />