Home > Blockchain >  How to add CSS code inn to external JavaScript file?
How to add CSS code inn to external JavaScript file?

Time:06-15

I am using a external CSS file and I have use CSS for the toggle. Where do I add following CSS codes?(In html file or the top of the external JavaScript file?)

.mystyle {
 
  background-color: green;
  color: white;

}
.mystyle1 {
 
  background-color: red;
  color: white;

}

Script.js

function myFunction(str) {

 var element = document.getElementById("btn1");
 var element1 = document.getElementById("btn2");
   
   
   if(str==1){
   
   
   element.classList.toggle("mystyle");
  element1.classList.remove("mystyle1");

   
    }else{
    
   element1.classList.toggle("mystyle1");
   element.classList.remove("mystyle");
  
  

    }

CodePudding user response:

Don't Mashup CSS with JS, keep those separately. you can try the below example:

function myFunction(str) {
    var element = document.getElementById("btn1");
 var element1 = document.getElementById("btn2");
  
   if(str==1){
   element.classList.toggle("mystyle");
  element1.classList.remove("mystyle1");
    }else{
    
   element1.classList.toggle("mystyle1");
   element.classList.remove("mystyle");
   }
}
.mystyle {
 
  background-color: green;
  color: white;

}
.mystyle1 {
 
  background-color: red;
  color: white;

}
<div id="btn1" onClick="myFunction(1)">
btn1
</div>
<div id="btn2" onClick="myFunction(0)">
btn2
</div>

CodePudding user response:

You have to add in a html file if it is a external file. reference

CodePudding user response:

  1. You can not add CSS Directly to a JS Code
  2. If you want to change CSS through JavaScript Code, you would need to add/remove each property using JS Code. For example, if you want to remove opacity from a certain element on click of another element, you can use:

const element = document.querySelector('class_name');
element.style.opacity = '0';

  • Related