+ 2
Which is the best way to implement CSS
I was reading about selectors with jquery and I made some practices to understand better, and I could see that the classes for css could be added by jquery and not in html directly. Which is the best way, what advantages it has and which disadvantages. I'm talking about some like it: Html way : <div class="mystyle">hello</div> Jquery: $("div").addClass("mystyle"); Thanks community. Sorry if I don't give the best explanation about it, I refer to add classes to after implement css
3 Réponses
+ 13
I never heard of implementation with jQuery, but i prefer implement all external files in the <head> of my HTML, for prevent confusion with files.
I mean, if i implement all my external resources in the <head> it's more easy know where i can find my files.
Post Scriptum: I reading something about the implementation with jQuery, a user in StackOverflow has used the ".append()" method with the <link> tag as argument... so, (except for spefic cases) i think that's more clean implement directly in the <head> your CSS/JS files.
[ EDIT FOR YOUR EDITED QUESTION ]
With jQuery methods (or property ".className" in pure JS) you can create toggle effects (and much more). For example, if you have two classes, you can create a toggle effect with them:
// .hide { display: none }
$(".el").click(function(){
this.toggleClass("hide");
})
In this example you can hide/show an element, this is just a basilar example. So, you have to use the ".addClass" method when you want to create advanced effects for your elements.
What are the advantages? Nothing, are two different things... declare class in CSS only if you have not need of effects for your element.
(Do you never heard about sidebar? In a sidebar there is a toggle effect show/hide)
+ 3
i think using the HTML way or style should be better and more faster..
because in this case all external files has to be imported..
just imagine importing the CSS, and then importing the jQuery again just to implement the CSS on the HTML markup ..
if its the effects then its a go for jQuery..
but i'ld rather use HTML:
<div class="close">x</div>
..
than:
$("div").addClass("close");
it kinda makes your site hard to manage.
as this even returns all div tags in the DOM in an array.
so you therefore have to know the index of the div tag you want to specifically apply your css to..
e.g applying css to the second div tag will then be..
var div = $("div");
div[1].addClass("div2");
pain!
the HTML method is 80% more pleasurable.
😊😇
0
With the <style> element you can add css directly to html. The tag is usually nested in the <head> tag. Also many elements in html have a style attribute, where you could make specific stylings...
But it's probably best to keep your Css in a separate file and link to file in html.
This way you can have all your styles separate from your markup and organized in one file. I'd suggest even limiting css use in jquery to only when you find it necessary for interactivity.