Is there a better way to change css attributes dynamically

I am trying to change CSS attributes dynamically for given elements in a document, my current solution looks 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 of name1 to all elements of the img class, then the code:

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

my question

Is there a better solution for a similar problem?

+4
source share
2 answers

Yes. Now you define name1 and name2 every time you only need to use toggleClass with the 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> 
+6
source

JQuery css() function can process an object of key / value pairs in one call: http://api.jquery.com/css/#css-properties

 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)"}; $(element).css(effects[choice]); } 
+1
source

All Articles