Toggling visibility with javascript versus with CSS [closed] - javascript

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.

Related

How to prevent an element from being modified by css? [duplicate]

This question already has answers here:
How to really isolate stylesheets in the Google Chrome extension?
(5 answers)
Closed last year.
I'm making a browser extension. It creates some UI on the page. In the UI, there are elements which are being forcefully modified by css depending on a website is opened. Aside from making it ugly, it also might break the whole UI!
The question is how to protect my poor elements from css terror?
There are multiple options such as iframes, extremely specific classnames, and adding the !important field everywhere. But your best bet might be to use a shadow DOM which allows for a hidden DOM tree attached to the regular (perhaps that third party website) DOM.
I've seen another thread on this post that might provide more detailed answers.

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

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

Is it O.K to eliminate 'a' tags? [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.
I get tired of the dotted box that appears when you click a tags...so that I started replacing them with p tags...and adding an event listener for click events.
I can't help but notice that other popular sites don't do this ( for example when you click Post Your Question on SO the annoying dotted box appears )
Is there any good reason not to replace a tags by p tags. I don't need any of the special a tag properties...in fact I have to use preventDefault() in my JavaScript to stop them from linking some times.
Is it O.K to pretty much eliminate the A tag?
This is a question regarding major modern browsers.
I'm about to rid myself of them...and am paranoid I'm missing something as I see them still in use pretty much everywhere.
No, this is not okay.
Anchor tags are needed for browsers that don't support your styling, and I'm just talking about old versions of IE. Remember that screen readers, text-only users, and browser plugins all expect to find your anchor tags.
As Dash has pointed out, bots such as search engine crawlers also need your anchor tags to be able to follow them and index your pages.
HTML is for document structure. CSS is for styling. It is important to keep this principal.
A note regarding that dotted box... that is there to show focus on an element. Not everyone uses a mouse you know. Some prefer to tab through the document with a keyboard, and that focus box helps with that. Even if you succeed in removing it with CSS... please don't.
Don't do this, because of html semantics. Screen readers and search engines may not be able to follow your link, for example.
If you don't want buttons and links to have a dotted box around them after they've been clicked, simply add a listener that blurs the element:
Look ma, no dots
There is also a CSS property you can set to not have dots too, but I can't remember it. Do a search or look at the Mozilla default stylesheet.
I disagree with the other two commenters a little. While it is true that it will break screen readers and not be backward compatible in general.....
IF you have a specific use case where you don't care about any of the above, well...it is your project. :)
And you COULD also mostly achieve this and keep the anchor tags by add the following to your CSS:
a
{
text-decoration: none;
}

Is it wrong for a website layout to be generated entirely by javascript? [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.
I'm working on a project currently and have written the entire page in Javascript.
I created a basic function:
create_element(parent, type, style, attributes);
Example Usage:
var container = create_element(document.body, "div", {width: "100%", height: "100%"});
var header_bar = create_element(container, "div", {width: "100%", height: "50px"});
var title_span = create_element(header_bar, "span", {fontSize: "18px", fontFamily: "arial", color: "black"});
title_span.innerHTML = "Example Website";
And so on...
I use this approach for the entire layout of the website. Is there a huge disadvantage to using this method? The obvious one is that fact that there may still be people out there with JS disabled.
Is there a tangible difference in page load times if Javascript is creating and rendering the items rather than them being hard coded into the HTML?
Thanks!
TL;DR -
Created a create_element function, and use it to draw all elements onto the screen. Including the base layout for the page.
There are a number of issues that you'll run into when you try to dynamically generate non-dynamic content:
Maintainability will become very difficult. If you want to make a sweeping change to your site, you're going to have to edit JS rather than just changing CSS or some HTML.
SEO - Google can't index dynamic data. This is not good if you want your site to be found via search engines.
You are mixing your layers. By not separating concerns (your views vs. your content vs. ...), you, again, increase maintainability issues and create a problem for your future-self or another developer who has to touch your code in the future.
Now, it's not wrong to do some dynamic generation - but do it appropriately. I would highly advise against dynamically generating content for your entire site.
Update Based on Comments on Original Question
That's great you enjoy JS. And, I definitely agree that HTML can be a bit boring. But, if you are properly separating your concerns, you really should have to write very little HTML and can quickly get back to what you enjoy coding in. But, be careful that you are not trying to force fit a language into something it was not meant to do when another language was created to do it perfectly. (Hammer/Nail Rule)
Also, don't forget that HTML5 and CSS3 is extremely powerful. You can do a lot with it and never have to even touch JS (assuming that meets client needs).
One major problem is that Google will not index any content of your site if you build it like this.
Also, this way your content, your logic and your styling will not be separated, which i think is a huge benefit if you use html / css in seperate files and a server side scripting language.
It is not wrong for an entire website to be generated by javascript based on the response from server if you ensure that metadata used for rendering the page is not evaluated as a whole as this leads to security issues.
In my opinion, it would be really better to use html as it is, if it's not dynamic content.
furthermore, having separate CSS files is more appropriate than setting it inline.
BackboneJS does this. You just have to ensure that JS is used client-side to complliment server side rendering, and that any rendering done solely on the client is capable of being in whole or part on the server as well.
There's no reason that a pages contents couldn't entirely be generated by javascript, but I wouldn't endorse this element by element approach. You aren't even using any style rules, only inline styles. Furthermore, in this case it'd be more maintainable to use some sort of templating mechanism for blocks of html, such as used in Underscore.js. (There are many templating solutions out there, like Mustache and Handlebars; I'm just giving one I've used.) There are several ways to maintain the html without it being in some javascript file somewhere, but even if it were in a javascript file, it'd be more maintainable than this element by element business.

Do you know an open source Javascript extraction/regexp engine? [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.
We are in need of a DOM parser, that will be able to run a bunch of patterns and would store the results. For this we are looking for libraries that are open and we can start on,
able to select elements by regexp (for example grab all elements that contain "price" either in class, id, other attributes like meta attributes),
should have a lot of helpers like: remove comments, iframes, etc
and be pretty fast.
can be run from browser extensions.
Ok, I'll say it :
You can use jQuery.
ups :
it is a very good dom parser
it is very good at manipulating the dom (removing/adding/editing elements)
it has a great and intuitive api
it has a big & great community => lots of answers to any jquery related question
it works in browser extensions (tested it myself in chrome and it apparently works in ff extensions too : How to use jQuery in Firefox Extension)
it is lightweight (About 31KB in size - minified and gzipped)
it is cross-browser
it is definitely open source
downs :
it doesn't rely on regex (although this is a very good thing - as dda already mentioned), but regex can be used to filter the elements
dont know if it can access/manipulate comments
Here's an example of some jquery action :
// select all the iframe elements with the class advertisement
// that have the word "porn" in their src attribute
$('iframe.advertisement[src*=porn]')
// filter the ones that contains the word "poney" in their title
// with the help of a regex
.filter(function(){
return /poney/gi.test((this.title || this.document.title).test()));
})
// and remove them
.remove()
// return to the whole match
.end()
// filter them again, this time
// affect only the big ones
.filter(function(){
return $(this).width() > 100 && $(this).height() > 100;
})
// replace them with some html markup
.replaceWith('<img src="harmless_bunnies_and_kitties.jpg" />');
node-htmlparser can parse HTML, provides a DOM with a number of utils (also supports filtering by functions) and can be run in any context (even in WebWorkers).
I forked it a while back, improved it for better speed and got some insane results (read: even faster than native libexpat bindings).
Nevertheless, I would advice you to use the original version, as it supports browsers out-of-the-box (my fork can be run in browsers using browserify, which adds some overhead).

Categories