Removing effect of a CSS selector - javascript

My requirement is a bit tricky. I have a mark-up as below: (just an example, real mark-up is very complicated)
<div class="classA">
<div class="classB">
<p class="classC">
<span class="classD">
</span>
</p>
</div>
</div>
As you can see above, there are four CSS classes classA, classB, classC, classD associated with the markup.
Also I have used jQuery to bind events using these selectors.
My Requirement: I want the jQuery event binding to work and at the same time, the CSS should not get applied i.e. I want to negate the impact of CSS styles from a UI perspective, but from functional perspective jQuery event handlers should still work.
So, is it possible to override the CSS selectors such that their styles don't get applied to my mark-up elements ?
example below:
div.classA div.classB p.classC span.classD{
color:red;
}
I don't want the font color to be red, so I tried to override the selector as follows, but its not working:
div.classA div.classB p.classC span.classD{
color:red;
}
div.classA div.classB p.classC span.classD{
/*no styles here*/
}
Please help !!

Then just delete those classes from css. jQuery will still work though.
There is no requirement that only classes used in css have to be used in jquery.
For example:
<div class="someUnknownClass"></div>
Even though, there is no someUnknownClass defined in css, $('.someUnknownClass') will still work.

Use another class name for the selector. So you have classA for the css and classX for the selector.
If you don't want the styles applied. Then you could use $('selctor').css(); to over write the styles. Bit hacky!
OR.
Add a class that over-rides the css. Or remove the class that holds the css.
using: $('selctor').addClass('no_styles'); OR $('selctor').removeClass('current_styles');

I don't know any mechanism allowing to do that the way you want it.
the work around i would suggest would be binding your events on anoter css class and doing something like this :
$('.classD').addClass('eventClassD').removeClass('classD');
$('.eventClassD').on('myEvent', function(){...});
like this you will still have events binded to your elements and would get rid of all the css.

You want to do it without modifying the JS? There's no clean way to do that. But try this.
Presumably you will have something that distinguishes this special set of elements to distinguish it from other elements, of which styles' you want to retain. This is difference probably manifests itself in the form of a different parent container. Just copy the set of CSS rules that affect these classes, and prepend this parent CSS selector with the pre-class values.

"Basically, I do not want to touch the js code, and only if something can be done on the css front, then my requirement is achieved."
If that is all you need, then just remove all of the css definitions from the page.
$("link,style").remove()

Related

Understanding .removeClass in jQuery

Can some one please explain to me what exactly is this jQuery call doing
$("header").removeClass("alternative full-width").addClass("full-width");
What exactly is it doing to the CSS file, Many Thanks
removeClass() function will remove the css selector applied to the element. In your case, if the header element has css attribute with value "alternative full-width", then those will be removed and it will add "full-width"
I also observe that, the above code has two values and you're trying to remove those two and add one of them.
Instead you could do this -
$("header").removeClass("alternative");
since you wish to add "full-width" which is already available!
NOTE I assume the .full-width css value is constant in that field. If it's not the case, we may have to use hasClass() to determine the existence!
For more info on removeClass - https://api.jquery.com/removeclass/
What exactly is it doing to the CSS file?
It has no effect on the CSS file
Can some one please explain to me what exactly is this jQuery call
doing
it remove the classes ( alternative and full-width )from the header with removeClass() and then it add the class ( full-width ) with addClass()
Header Element
$("header")
Select a header tag via JQuery
.removeClass("alternative full-width")
This method remove the "alternative full-width" class
.addClass("full-width")
This method add the "full-width" class.
As a matter of fact the JQuery it doesn't do anything in the CSS file.The only thing that is done with this example is to inherit the class properties that you have alredy define in the css file

Javascript vs. CSS for swapping elements

I have a rather lengthy (~100 fields) form that has certain elements which are toggled between a "quick" and a "full" quote. This toggles 75 of the fields from hidden to visible. Currently, I do this via some simple jQuery:
jQuery('.full_quote').show();
jQuery('.quick_quote').hide();
I realized that this could be accomplished in a different way using CSS to do the work for me:
## Javascript:
jQuery('#quote_form').toggleClass("full_quote quick_quote");
## CSS:
form.toggle-form.full_quote .quick_quote {display: none;}
form.toggle-form.quick_quote .full_quote {display: none;}
So the bulk of the question is: Which is better to use when performance is concerned?
My initial thought is that the overhead of iterating over the results in jQuery will take more time than the CSS. I do not have a way to test this, however, so I'm curious the community's experience.
Rather than defining new custom classes, or using jQuery's show and hide methods, I'd actually advise a third option.
Add a [hidden] attribute to whatever element needs to be hidden, and remove the attribute when it needs to be shown:
JS:
$('.foo').attr('hidden', true);
To make sure that this is supported cross browser, you'll need to add a bit of CSS:
CSS:
[hidden] {
display: none !important;
visibility: hidden !important;
}
This also gives you the ability to override how "hidden" elements are styled, which can be useful for debugging.
When you want to show the element, simply remove the [hidden] attribute:
JS:
$('.foo').attr('hidden', false);
It would be nice if jQuery implemented show and hide to utilize [hidden], instead developers need to take care when using show as it will override any stylesheet declarations for display when it adds a display style inline.
Both are essentially the same. JQuery does a very similar the same logic internally. (See How does jquery's show/hide function work?). And it is not like your CSS apprach does not use javascript at all (in that case, it would be the better option)
So,
jQuery('.full_quote').show();
jQuery('.quick_quote').hide();
makes sense (you are using JQuery anyway, why not use all of its functions) s a lot more readable, and

Separate ID and Class for JS and CSS

In several jquery tutorials, separate ID and Class are used for JS and CSS. for example
<div id="test" class="test">TEST</div>
As ID is used in the jQuery code, and Class is used in CSS. To me it is easier to not introduce Class and use ID for CSS rule too. Is there any advantage to use css-less ID for javascript?
EDIT: Thanks folks! I know the difference between ID and Class; I am asking why some use separate ID and Class for JS and CSS when one is sufficient. Here, the matter is the necessity for uniqueness of ID. The case is separating JS and CSS tasks (while they are closely entangled).
EDIT2: As requested, I give a typical example: this Tutorial. Look for actionsBox; .actionsBox has been used for CSS and #actionsBox for JS. As you can see there is only one <div> so ID would be enough for styling.
Read “Don't use class names to find HTML elements with JS” for some reasons why you may want to avoid using classnames in JavaScript.
This all boils down to personal preference, really.
Edit: #Sharon commented a link to a great article that discusses the drawbacks of using id selectors in CSS.
One reason people might only use classes in CSS is the specificity of the id selector.
If you’ve got two style declarations for one element, and they specify different values for a property, then the style declaration with the more specific selector wins out.
For example:
HTML
<div id="test" class="special-test"></div>
 CSS
#test {
color: red;
}
.special-test {
color: blue;
}
The ID selector trumps all other selectors for specificity (see http://www.w3.org/TR/selectors/#specificity for the rules), so here, the <div> will be red.
People who added class="test" to the <div> would presumably have written this:
HTML
<div id="test" class="test special-test"></div>
 CSS
.test {
color: red;
}
.special-test {
color: blue;
}
When both style declarations have selectors with the same specificity, the later declaration wins out, so here the <div> would be blue.
Personally, I’ve never found that to be a problem. In the first example, all you have to write to make the <div> blue is this:
#test.special-test {
color: blue;
}
But I guess some people find this aspect of specificity unnecessarily complex, and so avoid it by only using class selectors in their CSS.
(And I assume they keep the id because it’s faster to retrieve a DOM element in JavaScript by id than by class.)
You can use both ID and Class with both javascript and css. For example:
CSS
/*ID as identifier*/
#some_id {
<css attributes>
}
/*Class as identifier*/
.some_class {
<css attributes>
}
Javascript:
/*Get by ID*/
document.getElementById("some_id");
/*Get by class*/
document.getElementsByClassName("some_class");
The difference between the two is that ID will, or at least should be, unique and therefore will only affect or return a single element when applying css rules or selecting via javascript respectively. Class on the other hand is for affecting or selecting elements of a similar nature or classification.
If you had a car park with ten cars in it and you were to say "I want the car in space number three" you'd expect a single return whereas were you to say "I want the Fords from the car park" you'd expect to return every car in the car park which was a Ford. Css and javascipt use of ID and Class is no different.
EDIT: As per the OP's new redefined line of questioning.
css and IDs:
Css can harness IDs as an anchor so that the contents of a uniquely identified DOM object. Consider the folowing piece of css.
#some_id tr:nth-child(odd) {
background-color:#666888;
}
In the above example the css is tied to a unique identifier which in this case the ID is assigned to a table but the css rules themselves are applied to the odd rows within the table. In other words the css in this case affects table row elements where TR itself is an object class (not to be confused with css class).
In short, for ID at least, it is useful to use IDs within css and when you consider that jQuery and the likes of support Class-based queries using Class for selection within javascript is also useful.
Curious about the dual nature of "ID" in javascript and CSS. If you visit this example from w3schools: http://www.w3schools.com/js/tryit.asp?filename=tryjs_blocks
you'll see the which is "naming" this particular <div> with the name "myDiv". This is because javascript getElementById("myDiv") is used later to modify the text contents of this specific <div>
BUT - if you add the line of code:
<style> #myDiv { color:blue; } </style>
you now have a CSS id with the same name as the javascript <div id>
The sample code in the w3schools does indeed change the color of the <div> called "myDiv" to blue. But when you push the "try it" button on that page, the CONTENTS of the javascript <div> also changes, which is the point of the w3schools example. Ie., it's teaching you that getElementById("myDiv") is how you can retrieve and modify contents of a named <div>
But because the identically named CSS #myDiv id is in force the <div> contents are changed, and they remain blue due to the style sheet.
So when you see a <div id="myDiv"> inside an HTML page, how can you readily tell if this <div> wants CSS id treatment? Or if this <div> will be referenced by some javascript getElementById() method?
Maybe you should check out the differenc between ID's and Classes:
http://css-tricks.com/the-difference-between-id-and-class/
I have never heard of using classes only in CSS and ID's only for JavaScript.
The main thing is ID's are unique, thats why they are called identifiers. If you have the same styling of a div over and over again on your webpage you should use a class to style them.
EDIT: It's not common or maybe its not allowed, I'm not sure, that ID's start with a number !
You can use id and / or class in JS and / or CSS. It all depends what you want to select. If you want to select a single DOM element, feel free to use id. If you want to select a group of related elements you might be better off using class.
Id should(read: must) be unique. A class is a set of object that have similarities, for example all lists on the page should look the same (but then you should use the list selector instead of a seperate class for it.
They have different purposes.

Modify dynamically created jQuery checkbox button's css

I'm creating a series of jQuery checkboxes in a loop like so:
var checkbox = $('<input>').attr({type: 'checkbox', id: checkbox_id);
panel.append(checkbox);
panel.append($('<label>').attr({for: checkbox_id}).html(checkbox_name);
checkbox.button();
I have a css class called my-style that defines things like border-radius, padding, and line-height. I want my-style to override the attributes defined by jQuery's theme for only the checkboxes I've created.
I tried checkbox.addClass("my-style"); and panel.find(".ui-button-text").addClass("my-style"), but neither works correctly. Some css attributes do overwrite jQuery's default values, like border-radius, and others don't ever seem to be able to be overwritten like line-height and padding. I even tried to enforce css attributes directly by panel.find(".ui-button-text").css("line-height", 1.0);, but that doesn't work at all.
I understand that I could just modify the jQuery theme directly by changing the css code in there, but doing so would affect all buttons made, which is not what I'd like to do.
UPDATE:
One way I've managed to address this issue is by specifying the style tag directly. So the code above becomes:
var checkbox = $('<input>').attr({type: 'checkbox',
id: checkbox_id});
panel.append(checkbox);
var label = $('<label>').attr({for: checkbox_id,
style: "font-size: 0.6em; border-radius: 0px; margin-right: 0.3em;"}).text(checkbox_name);
panel.append(label);
checkbox.button();
label.children().attr("style", "padding: 0.2em 0.4em;");
While this solution works, it's unsavory, as I'm mixing JavaScript and CSS code together.
By writing in the style attribute, I can override jQuery UI's CSS. One thing that's been discussed here is using more specific CSS selectors that will be given more weight than jQuery UI's CSS classes. A more specific selector would be something that has the checkbox's ID. The problem with this approach is that checkboxes are dynamically generated, and thus so are checkbox IDs. It's therefore not feasible to have more specific CSS selectors from what I understand.
Is the problem that the class isn't getting applied to the element, or that the class isn't doing what you want it to do?
If the latter, can you paste the css code for your class?
It sounds like your CSS selector is not specific enough, you have two options here
Be nasty and declare your CSS properties with !important to override anything else selected
Write a more specific CSS selector
The latter is the better option, as you will have more control over your styling at a later stage. In case you don't know much about CSS selectors take a read of this (http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html) which should help understand writing more specific selectors and the value of each selector type.

How to make the effects of jQuery's $(element).css() persistent?

For example, with a font-size switcher/button, if I use
$('#container p').css('font-size', '24px');
it works as expected, but if I later add paragraph elements to the container (via ajax, etc), they are not styled with the updated font-size. I am aware that this is the intended behavior of the .css() method. I am simply asking:
What's the proper approach to changing a style for a CSS selector, and making those styles persistent?
Right, well, when you perform that command, it styles all p elements in #container. If you want it to be permanent, you could create a <style /> element and add the CSS stylings there.
To elaborate, you could do something like this:
$(document.head).append('<style>#container p{font-size: 24px;}</style>');
What jQuery does in that line is equivalent to:
<div id='container'>
<p style='font-size:24px'>a</p>
<p style='font-size:24px'>b</p>
<p style='font-size:24px'>c</p>
</div>
For your particular case I'd get one of the stylesheets present in the document, like this:
var stylesheets = document.styleSheets
Which returns an array of styleSheet objects that contain the insertRule method, which you can use to add your new (permanent) css rule.
Cheers!
You cannot add the style directly w/ JavaScript, but you can however do this:
<div id="wrapper">
<div id="paragraph1">blah</div>
<div id="paragraph2">you</div>
</div>
and
$("#wrapper").css...
This way any paragraph you add to the wrapper will have the new font size...
Well you are adding style to exiting elements only, there is no way for jquery to know about the new elements.
The problem is probably that you are destroying the element upon which you have the style.
If you are bringing in via AJAX a replacement for #container, then all of the content will get destroyed and replaced with the new content. All of the <p> tags you added the style to will no longer exist, and it will need to be repeated on the newer entry.
What you could try is creating a class definition on the fly.

Categories