-1

I have a handmade responsive jQuery grid, elements in this grid are DIV's with float:left.

Their widths and number in a row are calculating on their container width changes. For example if container width 500px, than it can keep 4 elements in a row, elements width calculated accordinaly as 25%, if container width changes to 400, it can keep only 3 in a row with width 33%.

The calculation is not important, the question is what is the fastest way to change container's elements style? Now I do straitforward

$('.container .element').css({width:'25%'});

As I understand jQuery iterates each element and changes it's style. But what if I could dynamicly create a style:

.container.foo .element {width:25%;}

And just add .foo class to my container, than I guess this operation would be forced by browser, and it could be much faster.

Is it? Is it possible?

Vladimir
  • 361
  • 1
  • 3
  • 14
  • _"Is it possible?"_ Yes. _"could be much faster"_ Tried benchmarking both options ? – guest271314 Jul 04 '15 at 15:09
  • 1
    Consider taking a look at this answer: http://stackoverflow.com/questions/1720320/how-to-dynamically-create-css-class-in-javascript-and-apply#answer-1720483 – Mindastic Jul 04 '15 at 15:12
  • If there is a way to do it with jQuery, there's always a faster way doing it without jQuery. Really, just go for the straightforward solution. – Bergi Jul 04 '15 at 15:14

1 Answers1

0

The correct way to do it is to :

  1. Create the classes in your css. Every style you need.
  2. Add or remove classes with jQuery. addClass / removeClass

So yes, the second option is faster, cleaner and reusable. It's about 50% faster.

Community
  • 1
  • 1
Pobe
  • 364
  • 3
  • 13
  • I think OP is talking about creating also the class dynamically, not just applying an existing one. – Bergi Jul 04 '15 at 15:16
  • Maybe, still if it's a % you should be able to use CSS. It might become very messy to do it in jQuery. You can swap `.row25` to `.row33`, etc. – Pobe Jul 04 '15 at 15:17
  • At first I thought to create a dynamic classes, but predefined classes should be faster, and I think 10 classes up to 10 elements in a row per 10% width is enough. Thank you. – Vladimir Jul 04 '15 at 16:01