Jade conditional (if/else) to add class to div inline - javascript

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})

Related

Add or remove a class based on a condition

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.

JS syntax on style property

Please take a look at my small script that checks if a style is defined on an element already .
HTML :
<div id="la" style="width: 100px;height: 100px;background: #eee;">
</div>
And the JS :
var _str = document.getElementById('la');
/*A object literal that contains some pretty random set of css definitions */
var str_elem = {
'padding' : '40px',
'width' : '100px'
}
/*we are using the for loop to check if the properties defined in our obj literal are actually present in the element style definition.*/
for(var name in str_elem){
if (_str.style[name] == ' ') {
console.log('not present' + ' ' + str_elem[name] );
}
}
My question is about the if condition and the syntax inside it. Usually when we want to get an elements style we use the following syntax:
elementname.style.propertyname
But why, when checking if the element has a property, are we using the following syntax:
elementname.style['padding']
??
And why does this syntax throw an error :
elementname.style.propertyname
My script works fine, my question is about the JS syntax.
EDIT:: to condense my difficulty , let me rephrase my question :
if in the if condition that i have i use the following syntax :
_str.style.[name] (note the dot after style) , instead of what i currently have _str.style[name] , Why is an error thrown . ?
Because you want to check that the value of the name variable is present as a style in your element. If you write _str.style.name, you would be checking the definition of the style called name. Brackets allows you to dynamically check the property, or to check property with hyphens, for example _str.style['my-dashed-property']
By the way, considering that the style property is not present because it equals a blank string is weird.
The syntax obj.[name] does not work because the dot operator is for accessing properties via fixed keys, hence you look for a property called [name] and that is not allowed
Ok, I see the confusion you have.
Before everything else, read this article.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
In JavaScript, you can access the properties of any variable in two ways.
1) obj.propertyName
2) obj['propertyName']
Now, coming to your question:
_str.style.[name] // Error is thrown because it is syntactically wrong to be accessing the object properties like this.
Just console.log your _str.style and observe that it is an object.
So,
_str.style.[name] // Does not make any sense, syntax wise. Hence the SyntaxError.
And since, you are trying to access the object properties dynamically inside for loop, you write like this:
_str.style[name] // Here name is a variable whose value is dynamically set during each iteration of the loop.

addClass(undefined) vs. addClass(null)

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

What is the correct syntax for writing custom attributes in a jQuery method?

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.

JavaScript/jQuery "if" condition syntax

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'))

Categories