When should I control background image change with CSS vs Javascript? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
This is more of a general practice question that a problem specific one but I'll give an example of what I mean. There are a lot of things you can control with CSS that you can also do with Javascript, but is one better to lean on than the other?
Example:
I have four buttons in a nav that are given a class of "selected" when the section they're associated with is in view. So I could either write a CSS statement for each button (or have Sass do it for me with a mixin)
#home-butt.selected{
background-image: url(images/home-up.png);}
#about-butt.selected{
background-image: url(images/about-up.png);}
#work-butt.selected{
background-image: url(images/work-up.png);}
#contact-butt.selected{
background-image: url(images/contact-up.png);}
Orrr I could write something in javascript to do the same thing. (*I gave the images a title attribute that matched the image name so it could pull from there).
title = $(this).attr('title');
$(this).find('img').css("background-image",
"url(" + 'images/' + (title) + '-up.png' + ")");
So my question is which is better to use? Is it the javascript because it's less lines of code? Or the CSS incase javascript is disabled? Or is this a very situational question where there isn't always a right or wrong answer?
Opinions and rebuttals are welcome!

To answer your question about "is one better to lean on than the other?"
Keep in mind, that CSS has a specific purpose. To apply the look to your application. JavaScript on the otherhand, is mostly the feel of your app. Always prefer CSS over JavaScript when editing styles.
The only time that you ever should modify styles using JavaScript is when you have a dynamic application, and need to change styles based on some unknown variable. Even then, a lot can be achieved with just using CSS.
Also keep in mind that you are using jQuery. think about jQuery's constructor. it is a CSS selector.
With the concept of CSS pseudo-classes introduced, there is very little that you cannot achieve style-wise with CSS.

In many cases where Javascript developing makes what I'm trying to accomplish much more easy and other cases where CSS does that to.
" In the end each "language" has its appropriate place in web development and used wisely can enhance both development and user experience. Learn what those uses are (I recommend experience learning) and apply wisely. In my experience, set in stone rules such as "Never use JS when a CSS solution exists" (paraphrased) are rarely best in the practical world. "
If you are working with layout, use CSS, if your creating the look and feel use CSS, if your doing animations use CSS3
If you attach event handlers or reacting to user input use JavaScript.

Usually you want to use CSS, because it's much faster than javascript. Also there are going to be users with javascript disabled, which aren't going to see your enhanced presentation if it relied on js function.

The usual answer is, use CSS when you can, because it will work with JavaScript disabled, and also because you don't have to deal with issues like waiting for elements being available in the DOM before referencing them.
But sometimes it depends. Keep in mind that:
Depending on the selector or properties you're changing you may have issues with browser compatibility.
If you're changing the image like in your example, you may see it flicker while the new image is loaded. You can avoid that by using a sprite image, or preloading the images with JavaScript.

As a general rule of thumb, I would use CSS for styling and JavaScript only to "make the page alive".
So the best and the most ideal use of JavaScript is to add and remove classes from elements
- classes, which your CSS is depend on.

Loading the jQuery library to perform this simple task is unnecessary and relying on javascript to apply background images to your img tags is unnecessary as well.
If it can be done properly in CSS, and work in all browsers, then it should be done in CSS.
Javascript is for more advanced or complex tasks, which require interaction or animations that CSS can't provide for all browsers (due to cross browser compatibility issues - check out caniuse.com)
In your example, if the .selected attribute is being given dynamically by javascript for instance:
makeSelected(elm)
{
document.getElementById(elm).className='selected';
}
then i would still personally add the styling for .selected in CSS instead of adding the image through javascript.
If you're adding .selected based on the current page you're on and not through javascript then I would recommend using CSS.

I prefer CSS over Script for one main reason Browser compatibility
There are just soooo many times when one script code or the other isn't compatible in one browser or the other (cough or just IE)
With css I haven't had such issues yet (touchwood) and also if there were any issues CSS's won't affect as much as script's which just don't let any other following codes to execute.

Let me provide my opinion.
Personally I don't believe a website should have a lot of "gimmicks" in terms of designing.
BY gimmicks I mean hovering effects, music in the background(absolute no-no) or other "eye-catching details". All of this looks good the first time but subsequently visitors get fed up with this distractions.
Without deviating from the main issue. CSS/JavaScript for styling.
Well they do exist hand in hand. The best example for this would be Bootstrap library. Although I have never used it personally but it seems amazing what can be achieved using CSS and JavaScript.
So, We will need both to design spectacular website. CSS helps in the basic designing and to make the website more responsive we use JavaScript and its derivative libraries like Jquery for all the finer looking stuff

Related

Block specific javascript statements from executing "globally" from a client side perspective

Dear Stackoverflow Community,
as you might see, this is my first post and a rather specific question I believe.
Here is the problem:
It is possible to block javascript as a whole or specific scripts as far as i could find out. What however if i globally want to stop the execution of specific javascript statements?
Practical example:
A website is utilising several javascripts many of which are useful and I would like to participate in their functionality with the permanent exclusion of any code that references overflow:hidden. I perceive that (CSS-Snippet?) to be malicious code by design. It can be easily circumvented and fixed through executing your own code. That's not what I'm talking about though.
Probable solutions:
- Remove the browsers capability of understanding that particular code
- Enforce overflow:auto
- Apply overflow:auto when the website is fully loaded automatically
The aforementioned solutions seem very unelegant to me and as you guys seem like a clever bunch maybe you can think of something less superfluous and practical.
All the goto addons I've tried only offer 1-off solutions or the need to repeat the task of counteracting those code snippets.
Current solution:
var r="html,body{overflow:auto !important;}";
var s=document.createElement("style");
s.type="text/css";
s.appendChild(document.createTextNode(r));
document.body.appendChild(s);
void 0;
Isn't there a way to tell FireFox (or chrome) to categorically ignore every single attempt to alter overflow:auto or similarly (perceived) malicious codes?
If you really want to set a property for all the elements in the website you could try this jQuery code
$('*').attr('style', ($('*').attr('style') || '') + ";color:black !important");
Here I get all the elements in the page and add my custom property in their style. In my case it was a black color, but you can have your overflow set to auto.
Check this Fiddle and you'll see that I set many colors to the texts in the page, both with inline styles and through CSS and then the jQuery script forces all of them to be black.
The explanation is that an inline rule is more "powerful" than CSS rules, so if you set an inline rule to be important it is applied to the element instead of the CSS rule (as it overwrites it).

Mobile website too slow on the phone [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am building a prototype for a mobile section of a website. It uses no dynamic staff, just jQuery and Foundation 4. When I test the site in the iphone's browser, it's very very slow to load and to respond to touches. Can some experienced folks please tell me all things to make sure the site loads and operates faster on the mobile device?
All my images are saved "for web", so they shouldn't be a problem. Could it be slow because my CSS style sheet is very lengthy? I am not an expert at combining and applying one classes to a lot of things yet, so may be I have too many id-s and separate classes? Would that be a big deal in this case though? Also, could it be slow because I am using Foundation, jQuery and a Flexlider plug in and each of them has their own multiple style sheets and .js files? Should I throw away any files I am not using from their folders? Am I on the right track and what else can I do? Thank you in advance.
There are some things which helped me to make my mobile app more faster. I had the same issue as you, the screen response was very low.
Get rid of every unused code
I had a lot of commented code and files that i actually didn't use. This includes css styles that aren't used.
Do you even need classes or Ids?
Looking at my app, i had almost on any element a class or Id. Were i instead could use a element selector. here some more info about the selectors. Follow the DOM structure. I mostly used a class for groups and Ids for one specific element(which i almost never needed).
Check if you have css styles that doesn't add something
Sometimes you have multiple styles that doesn't actually add anything to it. A great example is using a float: *; and display: inline-block;. When using both of these on one element has no extra function as float makes the element inline-block by default.
optimize you script
With this i mean, see if you can shorter you codes with the same functionality. Using two almost identical functions? short them to one function. Also using premade function of your script language will really help you to make your code faster. So don't create your own sort function, but use the premade function.
For help on optimizing you code, i suggest you to take a look here.
jQuery selectors
Make your jQuery selectors more specific. For example:
You may have a div with class content.
<div class="content"></div>
Instead of selecting it with
$('.content')
You could use
$('div.content' )
jQuery can now restrict the search to DIV elements only.
More info fore more efficient jQuery selectors here
Store determenation code
When you get information, for example screenWidth minus the width of a other div, and you using this more then once, store it! This way your webpage hasn't to do the calculate over and over and can just get the variable.
Don't use 'big' plugins when using half of it
When you only use a small part of a plugin you're using, it's better to find or a other plugin or code it yourself. Loading the plugin files might harm your performence, would be a shame if it actually wasn't even necessary.
This is just a global view were I had a big advantage on and I hope you can find a fine use for this.
Feel free to correct me when I'm wrong.

Toggling visibility with javascript versus with CSS [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Just found out about the CSS tilde selector and it seems like it could be an elegant way to handle toggling input visibility.
The use-case I have in mind is when you only want to display an input to the user when they have checked a checkbox. Currently I do this with javascript and attach listeners to each checkbox, which then search through the DOM to find the appropriate input and toggle a class.
So the question is, why is this bad? And if it isn't, why isn't this prevalent? Why do we do this with .js rather than CSS? It seems to me they are both manipulating the presentation layer in fairly similar ways...
Bonus points for resources.
HTML is the Model, it contains the Data
CSS is the View, it contains the Styles
JS is the Controller, it contains the Interactions
This MVC structure makes for a powerful delegation of responsibility. When you want to change the state of a widget on a page, you can use JavaScript to change the available styling hooks:
jQuery used for brevity
$('#button').on('click', function () {
$('#widget').toggleClass('hidden');
});
CSS:
.hidden {
display: none;
}
Using this structure will easily allow you to change how interactions are performed. If you decide later that the widget should be animated, it's a simple change.
Using JavaScript also has the advantage of being backwards compatible. The percentage of users who have JavaScript disabled is remarkably few. While I highly recommend supporting people with JS disabled, that can often be done simply by showing all the content by default, and hiding things only for users who have JS enabled.
The use-case I have in mind is when you only want to display an input
to the user when they have checked a checkbox.
If you're planning to use the :checked selector for that, your app won't run in old browsers (IE < 9). If you're OK with this restriction, that is, only modern browsers concerned, CSS will do fine as well.
Using JS ensures that your site will run on older browsers too, provided the users have JS enabled.
You can also use a mix of both and it will ensure that your page works in modern browsers even with JS disabled as well as JS-enabled old browsers.
It is often easier to detect whether the browser has JS disabled (e.g. using a stylesheet inside <noscript>) than determining whether a browser supports certain CSS selectors.
Therefore using a JS solution allows you to easily place a disclaimer asking the user to enable JS for the page to work properly.
Though, again, if your site is not aimed at general public that may be using IE8 and below, the CSS solution will do just fine.
I would say if you can get away with using the tilde selector, or css in general, then go for it. CSS imho is a cleaner, usually more concise and superior performance way to accomplish the same thing as toggling the item in js. Plus, the browswer support for the tilde is quite good - see http://www.quirksmode.org/css/contents.html
There are times when you must use javascript to accomplish this, for example the element to hide is not a sibling or a descendant of the element in question.

Questions about JavaScript and a vertical, multi-level navigation bar

Is it possible to make a vertical, multi-level navigation bar using only CSS and WITHOUT using JavaScript?
Like the one in here:
http://www.dhtmlgoodies.com/scripts/slidedown-menu2/slidedown-menu2.html#
I am trying to avoid using JavaScript because browsers today has an option that can disable JavaScript codes. I don't want my webpages to be broken because of that settings. Should I even be thinking about this? Or should I just use JavaScript anyway?
I was hoping on using only CSS for this, though I'm not sure if CSS is enough for this.
EDIT: By the way, is there a CSS selector when you click an <a> tag? Something like 'a:click'. I only know a:hover.
You won't be able to have any sort of animation like that example, unless you use CSS3 animations, in which case you will have LESS support than if you used JavaScript.
If it were me, I would just use JavaScript to do it. If the user has it turned off, they will still receive the menu, just not the animation (if you code it correctly).
There are some examples here of what you can do with CSS:
http://www.cssmenus.co.uk/dropdown.html
CSS is mainly for styling your webpages, while JavaScript is mainly for giving them different behaviors and interactivity.
That said, CSS3 is doing a lot to change that. But, if you want a web page with any kind of Cross- browser support currently, that's not really an option.
Like you have said, users have the option of disabling JavaScript, which is a good thing for security. This, however, means that you should always try to make any JavaScript supplementary to your page, so there is still some functionality even if JavaScript is disabled.
If you want any interesting effects in your menu, you will need some mix of CSS and JavaScript, and if you define and apply your styles within your CSS documents and not from within your JavaScript, you will still sustain some level of usability

Using JQuery for CSS vs Stylesheet

Because I like keeping all source code in one file (per class), I decided to add all style and CSS using JQuery objects, i.e:
jquery : $('<div/>',
{
id:'Object',
css:{
height:'100%',
width:'69%',
color:'white',
fontWeight:'bold',
textAlign:'center',
backgroundColor:'#02297f',
marginLeft:'.5%',
'float':'left',
overflow:'auto',
borderRadius:'5px'
},
html : 'My JQuery Object'
}),
Now I know there is probably going to be some sort of performance impact, but my question is how much? Does anyone else do it this way? Am I overlooking a potential problem?
I like it this way because I can just use objects rather than having to cross examine a stylesheet and it keeps it better organized.
EDIT: This is for a Javascript application, not a web page. So disabling the Javascript will kill the webpage anyway.
There is certainly a performance impact. The script is only run when all the page is loaded, so it will give you problems when the page is first displayed.
Apart from that, you got no styling at all when you run a browser where javascript is disabled.
But most of all, it is a Bad Idea. CSS is for styling, for the looks of your page. HTML is for structure, and Javascript is for logic, interactivity. I think you shouldn't use the .css method at all. If you need to toggle styles in Javascript, use classes instead, which can then be styled using style sheets.
But this method of yours takes it a step further even. I think it's even worse than putting all the css in inline style attributes. I hope you are just asking this question to see how people respond. It must not be serious. :s
Your are doing it wrong.
CSS must stay in *.css files and Javascript in the *.js files.
There is this thing known as 3 layers of Web:
content ( HTML )
presentation ( CSS )
behavior ( JS )
First of all, yes, if you use JS to generate html and style it, this would have a huge impact on performance. But even ignoring it : you would make the code virtually unmaintainable.
If you want to have better organized stylesheets, then invest some time in expanding your knowledge in CSS, and looks at practices behind OOCSS.
Thats a TERRIBLE IDEA! Use instead http://xcss.antpaw.org/
I agree with the way you're doing it. I essentially use it myself. I am developing a html5 game and in that context what you are doing makes sense. In games, user events and system events constantly change the screen. You can only realistically deal with this via just-in-time styling. So using .css() is a great way to do this. I think in a game that sprites are so distinct that they require their own style object.

Categories