Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to change css attributes dynamically

I'm trying to change CSS attributes dynamically for given elements in the document, my current solution is something like this :

function changeEffect(element,choice){

  var effects = {};

  effects.name1  = {"-webkit-box-shadow" : "7px 13px 21px -1px rgba(0,0,0,0.5)",
                      "-moz-box-shadow"     : "7px 13px 21px -1px rgba(0,0,0,0.5)",
                      "box-shadow"          : "7px 13px 21px -1px rgba(0,0,0,0.5)"
                     },
  effects.name2  = {"-webkit-filter"    : "drop-shadow(5px 5px 5px #222)",
                        "filter"            : "drop-shadow(5px 5px 5px #222)"                       
                       };


  for(i in effects[choice]){
    if(effects[choice].hasOwnProperty(i)){
       // using jquery to easily apply changes
       $(element).css(i,effects[choice][i]);
    }

  }                       
}

for example if i want to apply the effect name1 to all elements with the class img, then the code is :

changeEffect('.img','name1');

my question is

Is there any better solution for similar task ?

like image 209
ismnoiet Avatar asked Mar 15 '23 03:03

ismnoiet


1 Answers

Yes. You now define name1 and name2 each time when all you have to do is use something like toggleClass with appropriate CSS

$(".img").toggleClass("name1 name2");

Like this:

$(function() {
  $("#click").on("click",function() {
    $(".img").toggleClass("name1 name2");
  });
});
.name1 {
  -webkit-box-shadow: 7px 13px 21px -1px rgba(0, 0, 0, 0.5);
  -moz-box-shadow: 7px 13px 21px -1px rgba(0, 0, 0, 0.5);
  box-shadow: 7px 13px 21px -1px rgba(0, 0, 0, 0.5);
}
.name2 {
  -webkit-filter: drop-shadow(5px 5px 5px #222);
  filter: drop-shadow(5px 5px 5px #222);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="click">Click</span>
<div class="img name1">Hello</div> 
like image 93
mplungjan Avatar answered Apr 26 '23 00:04

mplungjan