Sometimes I'd like to add class in chain, under some condition. What value would be semantically most appropriate to add no class?
Example:
$(".element").doSomething().addClass(condition ? "special-class" : undefined).doSomethingElse();
Or:
$(".element").doSomething().addClass(condition ? "special-class" : null).doSomethingElse();
Use $.toggleClass() instead:
$(".element").doSomething().toggleClass("special-class",condition).doSomethingElse();
As ruakh mentioned it, there is a difference. If condition is falsy, it will actually remove the class if it was present before. With your logic, the class can only be added, not removed.
jQuery checks input parameter like this:
typeof input == "string"
so either null or undefined will behave the same way
Related
I am adding / removing a class from an element’s classList based on a variable’s truthiness. However, I’m doing it in what appears to be an obtuse way:
if (myConditionIsMet) {
myEl.classList.add("myClass");
} else {
myEl.classList.remove("myClass");
}
Is there a way in which I could make this more sexy and dynamically call the add / remove chained function for example with a conditional operator such as:
myEl.classList.{myConditionIsMet ? add('myClass') : remove('myClass')};
The above is pseudocode, of course, and I would like as plain JS as possible.
There’s a toggle method on .classList which takes a second argument (force).
This boolean argument essentially takes a condition that adds the class if true, and removes the class if false.
myEl.classList.toggle("myClass", myConditionIsMet);
Your pseudocode js
myEl.classList.{myConditionIsMet ? add('myClass') : remove('myClass')};
can be translated to actual js
myEl.classList[myConditionIsMet ? 'add' : 'remove']('myClass');
which is not particularly readable, but does exactly what you described.
For readability, I would look at the toggle method.
I am trying to conditionally apply a class to an element but I can't get the syntax correct
I have tried the following but it does not work.
ng-class="{foo: bar === "true"}"
bar is a boolean value.
Also, the element already has a class attribute. Will foo be appended to the list of classes?
You shouldn't use the double quote on your evaluation, because it's closing your ng-class attribute. You can use the single quote if you want to check a string.
In you're case, if bar is a boolean value, you don't have to use quotes at all :
ng-class="{foo: bar === true}"
which is equivalent to
ng-class="{foo: bar}"
In case of a string, use :
ng-class="{foo: bar === 'your_string'}"
If your element already has a class attribute, foo will be appended to the list.
ng-class="{'checkedClass': trueVariable}
Here is a post explaning the same http://www.ecofic.com/about/blog/conditionally-apply-a-css-class-with-angularjs
Is there a way to do this inline in a jade template?
if(typeof fromEdit != 'undefined')
div#demo.collapse.in
else
div#demo.collapse
Would like to do this conditional check "inline" and the result would add the .in to the end of the div if fromEdit exists.
This works:
div#demo.collapse(class=typeof fromEdit === "undefined" ? "" : "in")
Try it out here.
If you don't want the class attribute to be added when there is no value, you can assign it undefined instead of an empty string. Here is the previous example, slightly modified:
div#demo.collapse(class=typeof fromEdit === "undefined" ? undefined : "in")
Update: Also, if you are using pug, you can now add as many class= declarations as you want with different conditions and they'll get concatenated in the resulting class attribute. e.g.:
#demo.collapse(class=cond1 && 'class1' class=cond2 && 'class2')
As documented at http://jade-lang.com/reference/attributes/:
The class attribute [...] It can also be an object mapping class names to true or false values, which is useful for applying conditional classes
the task can be also done by the following:
div#demo.collapse(class={ in: typeof fromEdit != 'undefined' })
Although it doesn't work here http://naltatis.github.com/jade-syntax-docs/ (I think they need to update something), but it works with jade#1.11.0 .
With pug 2 you can use this syntax:
div#demo(class="collapse", class={"in": typeof fromEdit !== 'undefined'}) Home page
more here: https://pugjs.org/language/attributes.html
Though an old question, I find that the following works since Pug includes object existence detection built in:
div#demo.collapse(class=fromEdit? 'in':undefined)
If it's not obvious, this checks if fromEdit exists and if it does enters in as the class, otherwise leaving the class blank.
Multiple conditional classes
p(class={"true-class": isTrue, "false-class": !isTrue})
I have a ternary ahead of variable instantiations. The problem is, that this is an incorrect way to assign a variable for an attribute.
$partial = $data.cell_info_box === undefined ? job_box : cell_info_box
$rel = $($data.$partial).attr('rel');
$klass = $($data.$partial).attr("rel").match(/job/) == null ? 'task' : 'job';
How can I provide my ternary like demonstrated but create callable attributes with my initial ternary's product?
Based on your comment, what you want is $data[$partial]. This syntax is used when you want to get a value from an object without knowing the key name until runtime. You may also see this problem incorrectly solved through the use of eval but this is the correct way.
I'm attempting to evaluate a class to see if it contains some text in my click handler, but I can't get my code to act properly. What am I missing?
The if statement is looking to see whether the class of the clicked object has the word "headline" in it.
$('[class^=edit_]').click(function(){
var element = $(this).attr('class');
var field = element.split(/_(.+)/)[1];
if ($(this).attr('[class*=headline]'))
{
alert("headline");
}
else
{
alert("not headline");
};
});
Is it possible to construct my if statement with something that evaluates the var field = element.split(/_(.+)/)[1]; since that is really where the information resides.
Something like:
if (element *= "headline"){do this};
I'm not sure I understand all of the "evaluators" that exist in JavaScript to know if I can evaluate a string like that.
Upon re-reading your question, there's an even simpler approach, just check the .className for the string you want using .indexOf(), like this:
if (this.className.indexOf('headline') != -1)
Previous answer:
The closest version to what you have, checking if an element matching a selector is .is(), like this:
if ($(this).is('[class*=headline]'))
But there's another method more appropriate here (if you're checking for a full class, not part of one), you can use .hasClass() like this:
if ($(this).hasClass('headline'))