Am I using too much jQuery? When am I crossing the line? - javascript

Lately I found myself using jQuery and JavaScript a lot, often to do the same things that I did before using CSS.
For example, I alternate table rows color or create buttons and links hover effects using JavaScript/jQuery. Is this acceptable? Or should I keep using CSS for these kinds of things?
So the real question is:
When I'm using too much jQuery? How can I understand when I'm crossing the line?

You're crossing the line if you're using jQuery to do things that can be done easily without jQuery. jQuery's purpose is to make life easier, but it shouldn't be at the expense of compatibility or usability.
jQuery most certainly shouldn't be used as a replacement for CSS -- think of the users who have JavaScript disabled.
I know this image is overused, but someone had to throw it in here:
Image Credit - bobince.

I don't think there is a "line" here, I think there are some straightforward things and some grey areas there you have to balance what you want. Advanced features, performance, compatibility, think of these are a triangle, it's hard to do all 3 as best as possible at the same time.
If CSS can do it, of course do it in CSS. If it can't be done in CSS use jQuery, but do't use jQuery where the overhead isn't needed, e.g. $(this).attr("id") can usually be this.id, many things are available strictly on the DOM and still in a cross-browser way.
When are you using it too much? When it's not needed, sometimes you need jQuery for cross-browser CCS3 selectors, sometimes you're using a CSS selector that's already available put it in the stylesheet. There are a hundred other examples, but if you can get by in a cross-browser clean way without it, then there's no need, things like fading aren't trivially done. If you need to include jQuery at all, there's no reason not to use .fadeIn() once you have (the code's been included, why duplicate it?)
JavaScript vs No JavaScript
As said in comments here your site should offer all the basic functionality without javascript, this usually isn't a problem, e.g. capturing a click and loading the content via AJAX...if you don't capture it they do a full page reload, this is an easy fallback to the standard behavior. However, all the "bells and whistles"? This is opinionated for sure, but I don't think you should bend over backwards to offer all the functionality without JavaScript. The user turned it off, they don't get the fancy stuff, that's fine...look at SO as an example, disable javascript disables a lot of non-essential features, you can browse around just fine, but commenting, voting, mainly actions aren't necessarily available without JavaScript.

If you turn off java script on your browser and your site/application does not run or look functionally with out it, then you have a problem.
JS is great, but it should never stop a user from using something you have built, IF it is disabled.

If it's something that is easily do-able in CSS, then ditch jQuery and do it in CSS. That way you don't have to depend on javascript execution for the look/feel of your application.

You use too much jQuery if you could set one class attribute instead of a lot style attributes. For example:
/** Select 400 rows and change the background colour **/
$('#table tr').css('backgroundColor', 'blue');
Instead of:
/** jQuery **/
$('#table').addClass('blueRows');
/** CSS **/
#table tr.blueRows {
background-color: blue;
}
To avoid jQuery styling, you could also set a class to the body so it's easier to style with CSS for Javascript-enabled browsers:
/** jQuery **/
$(document).addClass('JS-enabled');
/** CSS **/
body #table tr{
background: #FFF;
}
body.JS-enabled #table tr {
background: blue;
}

jQuery most often gets applied after the document has been loaded. I guess that if you can achieve the same thing with plain CSS, CSS is the way to go. Less load on the browser, and if someone doesn't have jQuery enabled at least there's still (some) style because of the CSS.

For example, I alternate table rows color or create buttons and links hover effects using JavaScript/jQuery. Is this acceptable? Or should I keep using CSS for these kind of things?
Really, it depends on your browser support. You can do zebra-striping on tables really simply with this code:
table.classname tr:nth-child(even) td {
background-color: #ddd;
}
But this doesn't work in Internet Explorer at all (although it should in the upcoming version 9). So if you need everything to look the same cross-browser, use jQuery instead.
For link hover effects, assuming you mean colour changes, etc. and not fancy animation, definitely use CSS since this is supported everywhere.

Ok, don't mark me as a troll...
If your web-app wont work in an environment that doesn't have JavaScript enabled or isn't compatible with JQuery, then just go with whatever is easiest for you to manage. There is no benefit to having visual support for an application if it doesn't actually work otherwise at all.
Tho if you want to make it work later without JavaScript support, then you should prob try to use css. But if you don't plan for no-JavaScript support, and it works, go with whatever is easiest for you

Related

Codemirror displaying incorrectly due to CSS

My CSS code is causing Codemirror to display incorrectly. See below:
How can I prevent my styles from affecting the elements created by Codemirror so that Codemirror will display correctly?
Even if I manage to tweak my CSS code so that both my page and Codemirror display correctly, it will be a nightmare in the future because any future styles may affect Codemirror. Also my CSS file is generated dynamically depending on values given by the client, which further complicates things.
One possible solution is to create a class called not-codemirror and apply it to every single element on my site, other than elements for Codemirror. This seems like overkill to me, especially considering most pages will not be using Codemirror. All pages share the same CSS file.
Also, I would prefer a non-jQuery solution, if possible. Thanks
EDIT
I now have it displaying as this:
It should look like this:
I added:
display: inline;
margin: 0;
padding: 0;
to .CodeMirror span in codemirror.css.
Codemirror markup has a specific class .CodeMirror (at least in latest version it's present);
So if you want other styles not to clash you can use .not :
clashing-selector:not(.CodeMirror)
You know the problem lies in conflicting CSS declarations, so I would suggest giving each of yours or Codemirror's tags which are conflicting a class to clear up confusion. It's pretty clear that Codemirror should be the one you change since it sounds like you are fairly well bound by your site's dynamic CSS. This 'targeted' solution is a lot simpler than attacking your entire site with not-codemirror tags (and thankfully, does not involve any jQuery), and I don't think it will be that difficult to figure out what to change in Codemirror's source if you are relatively familiar with your own CSS.
If it turns out you run into issues with specificity as well, you may be able to justify using an !important tag, but I would try to stay away from that on principle.

Why isn't there a flexbox polyfill for older browsers like IE9?

Are there some problems that prevent people from creating it? Is it too complicated?
Maybe there is just no need for that?
Was it created it already and I just can't find it?
I imagine it to be a js based library and work this way:
It checks if the browser supports flexbox natively;
If it doesn't, it parses CSS and checks if an element has flexbox related rules;
If it does, it tries to emulate these rules via javascript by calculating all positions and sizes of the children elements and position them using position: absolute;.
Basically, the same thing that Masonry and similar libraries do, but with flexbox rules. Would that be possible to do?
Edit: this question doesn't explain why it can't be done.
There is actually a library that does exactly what I wanted: https://github.com/jonathantneal/flexibility
It's in the very early phase of development, but hopefully it will be viable soon.
"emulate these rules via javascript" is the "most impossible" part.
flex box is purely position:static thing, you cannot move it on
position:absolute layer (there are too many things behind this);
flex box calculations are made on so called rendering tree that is not available to JS;
In order JS to be used for static layout purposes browsers should have a mechanism to hook up users code to rendering tree formation and layout:
div { layout: myFlexManager url(my-layouts.js); }
But as soon as browsers will have such a facility the flexbox will be thrown away as this is the worst and ugliest CSS spec ever produced - community will come up with something better - simpler and more practical.

performane issue- css vs javascript vs jquery

I am a beginner in web-designing. I use css, javascript, jquery for web development.
There are times when an effect can be achieved with all of the three. Like a simple mousehover effect can be achieved with css :hover, javascript's onmousehover(), and jquery's $(#id).hover()
jquery fade-in, fade-out effect can also be simulated using css transition.
My question is: If an effect can be achieved using all three. Do i need to give preference to stylesheet language or javascript or jquery. using which among above will increase performance and will load the webpage faster.
First of all give a preference to that way which you can do faster (computers cost a little, programmer cost a lot). Also pay attention of how you do it - if you have to write tons of css code instead of couple lines in jQuery - use jQuery for sure.
css speed > javascript speed > jquery speed. As i seen some benchmarks native js is like 10-100 times faster than jQuery (depending on browser/selectors etc...).
Depending on situation - if you really need to optimize your interface -> find a bottlneck first, dont't optimize too early, it's evil
jquery has the advantage of working across multiple browsers but suffers some slowdowns to do this. A custom javascript solution may or may not work on all browsers, but it might be faster than jQuery if you're really good at writing fast javascript. Using css to achieve an effect has the advantage of working on all browsers that comply to the css standard and browsers should be highly optimized to render css very fast.
I think it's more an issue of what browsers you want to support, personal preference and coding styles than it is an issue of speed, but here is some information and benchmarks:
Which is faster? - modifying css property or adding class in jquery
http://jsperf.com/jquery-css-vs-native-dom/16
http://jsperf.com/jquery-css-vs-css/4
http://jsperf.com/jquery-css-vs-getcomputedstyle/2
Edit: Agree with Sergio, early optimization is the root of all evil. Write the code first, look for bottlenecks and treat them last.
Depends on what you want to achieve or the scenario.
I personally like css,but sometimes to achieve cross browser compatibility or some fancy effects i use jquery.
Jquery can be customized a lot,lots of options are also available,but it affects the page loading time. I prefer jquery or javascript.
With CSS3,lots of effects that could only be done with jquery are achievable now,but it only supports modern browsers.

is positioning with javascript a good practice

I've just learned javascript and jquery a few weeks ago, since then I always use it to position all my divs and stuff in the screen by knowing the size of the screen and the window which I find extremely useful, but now I don't know if is this a good practice, cause it makes my web-pages fully dependant on jquery which I don't know if it may cause some troubles with different browsers.
I would really like to find answers like "Sure is a good practice, use all the scripts you want" cause I'm really loving this javascript stuff but well just tell what you think.
Use JavaScript for behaviors and CSS for styling.
Styling with JavaScript is slower and difficult for another developer/designer to figure out what you did.
Also if you use Firebug or Chrome Web Inspector you can not see where your styling is coming from.
Optionally set classes from JavaScript and not specific styling. You can transition between classes to create a nice effect. But at least your colleague can see where the styles are defined and change it.
I'm sorry, but I'm going to burst your bubble, somewhat.
It's somewhat OK to do it - as long as the page looks OK if you disable Javascript, as well. I would say it should look even better than OK. I would also say that you should only do that if the functionality of your site really demands Javascript, as well.
Keep in mind that a certain percentage of users will have Javascript disabled. I've seen sites that look horrible this way (I use NoScript on Firefox, and selectively enable Javascript as I browser), and a couple where nothing at all appears without JS enabled.
Bad.
As Darin notes, you can (and should!) use CSS for positioning and styling. That is what it was made for! Feel free to enhance the page with Javascript, but keep in mind what I say above!
You could use CSS for positioning and styling of elements. That's what it was designed for.
It's okay to use it for positioning in some cases, but using CSS is the better practice whenever applicable.
Well, In my opinion you should avoid it as often as possible. But I know sometime you don't have the choice.
And yea you can make great web apps using scripts.
It depends what you're positioning.
CSS should be your first choice for positioning standard, run-of-the-mill sections and elements of a webpage. To opt for JavaScript in these cases suggests a lack of understanding of CSS.
Likewise if you find yourself using JS to position things for different devices. Again, CSS has evolved; media queries came along for that. Rule: always exhaust CSS possibilities first.
That said, it would be oversimplification to suggest that JavaScript never be used for positioning. All of us, rightly or wrongly, have resorted (and it is just that, resorting) to JS in order to get things to look right cross-browser, particularly where support for older IEs is concerned.
But by far the biggest use case for JS positioning is for modern web aps and games. If you're building a game with random asteroids dotted around, JS is absolutely the choice for that, since the positions are based on calculation and computation.
Finally, bear in mind that when you position in JS, you are of course still using CSS. JS doesn't have its own, concurrent styling/positioning system - it simply sets CSS properties. It is simply able to do so more dynamically and conditionally than flat CSS.
It is almost certainly bad practise. Use CSS for styling - JavaScript to do this is slower, more work, and more prone to breaking.
If you're positioning everything absolutely (fixed coordinates) it won't look good on screens of different resolutions. There's no real answer to this question.. scripts have their place, and you can use all the scripts you want... Positioning all of the elements of your layout, however, is not a job for JS. Use CSS for that.
I'd start here: Starting with HTML + CSS
There is not one method for all situations. Each web application needs to employ the right tools and practices to achieve its goals. This varies so much between applications that there is not a "correct" answer to your question.

Is there any problem using JQuery/JavaScript to apply lots of CSS styles?

I want to apply ALL the CSS styles 100% with JQuery/JavaScript
But is is bad idea to do this?
Why would you create that overhead in javascript when straight HTML/CSS is fully capable of handling it? (in fact intended to)
Also, you're adding an unnecessary requirement to the styling of your site: having javascript enabled.
Main reason IMHO: Performance! Native CSS is much faster than JS.
Also worth mentioning:
Doesn't work for users with NoScript etc.
Overhead. Not such a big deal i think. There are more important things to optimize.
If you lazy load stuff, e.g. by using jQuery.load(), you have to reapply your styles to these elements. Not nice :/
Conclusion: CSS is made for styling, JS isn't.
If your visitor has javascript disabled, they'll see an ugly white page without any styling.
I don't see why you would do this, to be honest. It's not user-friendly.
Use a stylesheet.
A lot of people say to apply classes not individual styles.
You will see varying levels of performance degradation across different browsers. It's faster and cleaner to let the application render the styled HTML page because that's what it's optimized to do.
If you're dynamically loading content and already have fade effects/transitions so your content is only revealed after it's styled, you might be ok.
if you are going to do this, only apply styles with jQuery (rather than using javascript) to maintain cross-browser compatibility.
I would recommend against your approach because of the time it will take jQuery to loop through all of your elements and apply styles.
something like $('span').css(...); has to traverse the entire DOM and loop through a collection of elements. $('#title').css(...); does not have to loop through the entire DOM because it immediately knows where to look.
Also, browsers are designed to process stylesheets and render your styled elements very quickly.

Categories

Resources