Which of these is more efficient (i.e. faster):
$(elem).show();
or
$(elem).addClass(displayClass); // Where display class is "display: block;"
Or are they identical?
It depends what you're after, they do different things:
$(elem).show(); - shows the element, restoring the display from before .hide() or restoring the default display for the element type
$(elem).addClass(displayClass); - adds a class, always with a certain display, not really restoring what was there - this is less flexible
Which is faster? .addClass() hands down, you can test it yourself here, it simply does a lot less work than .show() does. However, it doesn't do as much feature-wise, so it's less flexible for the reasons above.
No, they are absolutely not identical.
There's a big difference between direct modifications to element styles and "indirect" modifications by changing the element's class, and that really should be pretty obvious. By writing cooperative code between Javascript and CSS, the class changes give you a lot more flexibility. The Javascript manages the state of elements, while the CSS drives the actual effect of that state.
The show() and hide() methods are handy and easy, but (in my opinion) managing state/appearance by class name is really a much more powerful and maintainable way to do things. In fact you can always write your own little jQuery plugins to add/remove classes that are meaningful to your app, to avoid having the class names themselves propagate through your code.
They're not identical; they work completely differently. They may in your case have the same effect, but don't count on it.
For example, addClass may not actually make the element visible in all cases. If the element has other styles which supercede the class (eg ID-level CSS, or inline styles, etc), then adding a class won't have any effect at all.
Also, setting display:block is only correct for elements that you want to be displayed as a block. If you've got inline elements (or worse, tables) and you try to display them as block, the results will probably not be what you're expecting.
Finally, .addClass() definitely involves more processing for the browser than .show(), so you're not making things any easier for your site by using it.
In short, if that's all you're trying to achieve, use .show() - it's the correct jQuery way to do it.
Related
I always romoving 'current' class of all siblings then add 'current' class to my clicked one. I want to know will it be faster only removing 'current' class of which has 'current'.seems to be a simple question, but I really want to know.
Yes, filtering the query to a smaller set of elements will perform faster, because there are less elements to check.
In modern browsers, jQuery will use native methods to query the DOM, so adding the selector has a negligible performance impact.
I don't think there's much difference, since there's only one "current". It doesn't matters too much for querying one more element or one less.
Usually I'll first find out the outer element to narrow down
$('#selectionDiv').find() ....
Depending on how many elements you are re-classing, the impact of the optimization will of course vary.
I tested it, http://jsperf.com/reclassing-all-or-one, using 7 (seemed reasonable for for example navigation tabs) divs and I think the difference was significant (reclassing all 30% slower than only one), percentage wise. If one cares about actual time though it may not be, but I can't really see any reason not do be distinct.
Here's my problem: I'm writing a WordPress plugin that helps budding CSS authors see how css applies to their theme in real time. It's got a numer of nifty features, except one, which is pretty crucial in my mind.
I want to allow them to click an element, see the full selector path to that element (that part is done), and then show them which styles in their stylesheet apply to it.
I have the full selector path to the element (html body div#page div#post-18.post h2.posttitle, for example), and I have their stylesheet parsed into individual selectors - but I can't figure out any way to compare the two. Some ideas I've had:
Use jQuery, and run every selector (in the stylesheet) to see what it returns. I'm not crazy abou tthis because it seems like a huge performance drag to check (potentially thousands) of selectors against the full DOM. On top of that, I've then got to compare the jQuery objects to see if they're pointing at the same thing - and based on what I've read about comparing objects, I'm not sure that will be a walk in the park.
Write my own, simple comparing function, and compare the full selector path with the css selector. I was pretty sold on this, until I started thinking about the various advanced selectors - : > etc.
Use sizzle (or similar), or somehow use jQuery's implementation of sizzle to just compare the selectors. They're running these selectors against the DOM, so surely they have the ability to just compare selector strings? Somehow?
I'm stuck. Any help is greatly appreciated.
Checking for equality in that complex structures (like CSS) is extremely difficult (e.g. you cannot determine this by testing for equal result sets, since they could behave entirely different under other circumstances). You might be able to figure this out using browser-specific APIs if they are available in JavaScript (e.g. Firebug displays stylesheets that affect the selected elements). Other than that, your first approach is the only possible one AFAIK.
Say you've got a menu that toggles open and closed with a button. My standard way of going about this would be to write the CSS for a closed menu, and write Javascript that specifies (or animates to) an open menu state.
Lately I've gotten into Active.js, a client-side MVC framework. It provides for view classes with builders for making DOM fragments, and those fragments can be given methods that handle things like animation and DOM state.
Something feels wonky about describing the initial state in CSS, and then describing alternate states in JavaScript. Without animation, it would be sensible to just do it all in CSS and just use javascript to add or remove DOM classes.
My other idea is to describe all of the states (folded, unfolded, red, green) of a DOM object in JSON (rather than CSS) and give my ActionView object methods for animating between those states. Is anybody doing this? Other ideas?
As far as animation goes, it wouldn't be a violation of DRY to have basic styling in CSS and then the animation or styling you can't achieve in pure CSS in javascript because you still don't have any repetition if done right. If you think its a more "pure" way to do things you can try to keep more of the styling in javascript or CSS, but those are just the languages you are using and if you consider them both expressions of the same underlying DOM its entirely appropriate to use the more expressive or compatible language wherever needed.
I typically take CSS as far as it will go and then start using jQuery to do the things that CSS can't handle or are not cross browser, like animations.
I'm making this search component that I can just load using javascript and have it work wherever I load it. The idea is that it does an AJAX-search, so I don't want to code that up every time I put one on the page.
So maybe on pages that I want to put it on that would look like this:
var searchBox = new Search(inputBox);
Ideally, I wouldn't really want to have to link a style sheet everytime I do this. I'm just wondering if performance takes a big hit if I just create tags and add attributes like this:
$('<div></div>').css({
'background-color': #002323, etc.
});
I feel like its only slightly more verbose, but it will be much easier to manage and use.
Or do you know a better way of doing this?
Maybe this question is brushing the surface of a bigger problem, which is about making CSS object-oriented. I don't want it messing up other things on the page if there are css attributes with the same name. Everything else I do is object-oriented. Are there any CSS solutions or methodologies for this?
Two things come into mind:
If you ever want to change the style, you will have to do it in javascript, possibly at several places.
Obviously, applying styles one by one instead of just adding a class is slower.
CSS was designed to make your life easier and honestly I think it wouldn't be very wise to not to use it, unless you have some javascript style framework that does a better job.
It seems to me that it rather depends on how much CSS you need to apply to this search component, and whether you need to be able to skin it for different sites. Assuming your javascript is all held in one external file, is it a big problem to create a basic CSS file to go with it, and use the script to dynamically insert a <link> to the CSS file above other <link> elements in the document?
That way you can reuse and skin it very easily, overriding the styles set in the default CSS for any particular site just by adding the appropriate selectors to that site's stylesheet. If you set them all with jQuery, it'll be much harder to change the skin.
The main problems of your search component are obstrusive JS and probably non-accessible tool (except if you took the ARIA road).
The one you're talking about is secondary.
You should use carefully named classes, I wonder what can be easier to manage than a class="warning" (background-color: #FE0114; ? no way)
What is the best method for applying drop shadows? I'm working on a site right now where we have a good deal of them, however, I've been fighting to find the best method to do it. The site is pretty animation heavy so shadows need to work well with this.
I tried a jQuery shadow pulgin. The shadows looked good and were easy to use but were slow and didn't work well with any animations (required lots of redrawing, very joggy).
I also tried creating my own jQuery extension that wraps my element in a couple gray divs and then offsets them a little bit to give a shadow effect. This worked well. It's quick and responsive to the animation. However, it makes DOM manipulation/traversal cumbersome since everything is wrapped in these shadow divs.
I know there has to be a better way but this isn't exactly my forte. Thoughts?
ShadedBorder is a good looking and easy to use Shadow-Library. check it out
You don't need to wrap those shadow-divs around the other content, just set them a little askew and place them on a lower z-index !-)
if your main problem is to navigate the DOM, just add a class and/or id to your element, and refer it with JQuery selectors. even better if you store the ref in a variable, so you don't need to select it too frequently
Although it is yet to have full cross-browser support, you might like to try using the CSS 3 text-shadow property.
It largely depends on how frequently your images will need to be changing, and the colored areas that they'll be covering. Because I'm guessing that you'll be needing to pay attention to IE6 compliance, most alpha-PNG solutions will cause such horrible jittery-ness that you'll spend more time in performance optimzation than you would have wanted to guess.
To solve this in the past, since our images are modified less than once a month, we call the images through a caching-PHP script which automatically applies the shadow using a pre-defined background color so we don't have to rely on any transparency. This results in faster downloads (fewer HTTP requests) and a faster-interface because there's less Javascript/CSS magic in the works.
I understand that this is a very old-school solution, and the above solutions would be entirely acceptable if your images were static, but being cross-browser compliant and animated will likely force you to do a solution of this style.