Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Css code in javascript function

Tags:

javascript

css

I have this javascript method:

<script type="text/javascript">
   function MyFunction(sender, eventArgs) {
       if (someCondition) {
           //css
       }
    }
</script>

The css code I want to be executed is:

<style type="text/css">
          .classInsideTheClassWhichEntersTheIf
          {
          background: url(Images/myImage.png) !important;
          }
</style>

but only for those cells that enter the if condition above. If I write it outside it works but for every cell. Is something like this possible? If yes, how to do it?

like image 859
petko_stankoski Avatar asked Dec 02 '22 00:12

petko_stankoski


2 Answers

There are several ways to do this.

Option 1.

<script type="text/javascript">
   function MyFunction(sender, eventArgs) {
       if (someCondition) {
          someelement.style.cssText = "background: url(Images/myImage.png) !important;"
       }
    }
</script>

Option 2.

 <script type="text/javascript">
       function MyFunction(sender, eventArgs) {
           if (someCondition) {
              someelement.className = "someclass"
           }
        }
    </script>

where,

<style>
.someclass{
background: url(Images/myImage.png) !important;
}
</style>

Option 3

 <script type="text/javascript">
           function MyFunction(sender, eventArgs) {
               if (someCondition) {
                  someelement.setAttribute('style', 'background: url(Images/myImage.png) !important;');
               }
            }
        </script>

Here is a pseudo code,

if(condition)
  someelement.style.cssText = "background: url(Images/myImage.png) !important;";
like image 88
Ashwin Krishnamurthy Avatar answered Dec 04 '22 12:12

Ashwin Krishnamurthy


<script type="text/javascript"> 
   function MyFunction(sender, eventArgs) { 
       if (someCondition) { 
          someelement.style.backgroundImage = "url(Images/myImage.png)"; 
       } 
    } 
</script> 

!important is unnecessary here, because inline styles override non-inline styles.

like image 26
Niet the Dark Absol Avatar answered Dec 04 '22 13:12

Niet the Dark Absol