I need to have a if/else statement inside a function. How do you check if an element (e.g. #cadrage) has a display style property? This is what I have found around the net and yet, it is not working..
if( $('#cadrage').attr('style').display == 'block' ) {
// do something
} else {
// do something
}
The jQuery .css() function seems to be what you want.
if( $('#cadrage').css('display') == 'block' ) {
console.log('It equal block');
} else {
console.log('It did not equal block');
}
http://jsfiddle.net/SamMonk/FtP6W/
Your code doesn't work because style property only contains inline styles, not those coming from a stylesheet.
To get the computed style, you can use css method:
$('#cadrage').css('display') == 'block'
Try this:
if( $('#cadrage').css('display')== 'block' ) {
// do something
} else {
// do something
}
You can get your element display property with the following code snippet
$('#cadrage').css('display');
Note that the css method can return any css property of your element so it is very handy.
Therefore your statement code will be:
if( $('#cadrage').css('display').display == 'block' ) {
// do something
} else {
// do something
}
Not exactly what you ask for, but perhaps what you are looking for...
You can use the :visible pseudo selector to check if the element is visible:
if( $('#cadrage').is(':visible')) {
// do something
} else {
// do something
}
Note that this doesn't actually check the display style, but rather if the element has a size so that it could be seen in the page.
Related
So I'm learning Javascript and I have a doubt on changing a global variable with boolean variable, while changing the attr of visibility on an element.
The code is this:
var lastView=false;
$("#idShipmentActionsCombo-icon").on('click', function(){
if (lastview=false){
$('#idShipmentActionsCombo-lb').attr('style', 'visibility: visible');
lastView=true;
}
else if(lastView=true){
$('#idShipmentActionsCombo-lb').attr('style', 'visibility: hidden');
lastView===false;
}
}
So #idShipmentActionsCombo-icon is the element I click in, #idShipmentActionsCombo-lb and this is what I want to show and hide depending on the value of lastView.
Thanks in advance, and I apologize for my English since it's not my main language.
Since you use jQuery use .toggle() method instead of booleans, conditions and style.
$("#idShipmentActionsCombo-icon").on('click', function(){
$('#idShipmentActionsCombo-lb').toggle();
})
Looks like you're missing a closing ); at the very end from your .on( In addition, there are a few cases where "===" and "=" are confused and where capitalization is incorrect. See this: http://jsfiddle.net/215sxj90/3/
In my opinion you're confusing assignment with logical operators.
The following is the assignment:
lastView = true;
and the following is the logical operator - comparison:
lastView === true
The latter should be used in your conditional statements - if, else if etc.:
var lastView = false;
$("#idShipmentActionsCombo-icon").on('click', function () {
if (lastview === false) {
$('#idShipmentActionsCombo-lb').attr('style', 'visibility: visible');
lastView = true;
}
else if (lastView === true) {
$('#idShipmentActionsCombo-lb').attr('style', 'visibility: hidden');
lastView = false;
}
}
I have a form with id commentform and if any logged in user visit the page a p tag gets generated under the form that with class logged-in-as. Now I am trying to check if that p exists and if not exists then do my validation which uses keyup(). Here is a small snippet...
$('form#commentform').keyup(function() {
if( ! $(this).has('p').hasClass('logged-in-as') ) {
....
} else {
......
}
}
});
Now the problem is that the if( ! $(this).has('p').hasClass('logged-in-as') ) is not returning me the expected result whether or not that specific p exists.
Can any of you guys tell me any other/better way to check this?
$('form#commentform').keyup(function() {
if($(this).find('p.logged-in-as').length == 1) {
....
} else {
......
}
}
});
You can do this to find it.
You can use
if ($('.logged-in-as', this).length)) {
But I would rather use a variable to store that state instead of relying on checking the presence of a raw tag : what if you change your HTML a little ?
Side note: Don't use overqualified selectors. $('#commentform') is faster and logically more consistent than $('form#commentform').
Check if an element witth class "xxx" exist
if( $( ".xxx" ).size() > 0 ) {
// EXISTS
}
Edit: forgot the dot ( ".xxx" )
I have a function that check if CSS value exists,
the problem is that I need the function to work only when the CSS class exists,
currently the function running all the time because I'm using else condition (that need to re do the if condition).
//use for #media only screen and (max-width: 767px) detection
$(window).resize(function(){
if ($('#mobile-view').css('visibility') === 'hidden') {
$("#product-gallery").insertAfter("#product-info");
}
else {
$("#product-info").insertAfter("#product-gallery");
}
});
You could use the :hidden pseudo selector:
if ($('#mobile-view').is(':hidden')) {
$("#product-gallery").insertAfter("#product-info");
} else {
$("#product-info").insertAfter("#product-gallery");
}
See also: .is() and :hidden
Change it to
if ($('#mobile-view').is(":visible")) {
$("#product-info").insertAfter("#product-gallery");
} else {
$("#product-gallery").insertAfter("#product-info");
}
you can use hasClass
if ($('#mobile-view').hasClass(className)) {
// put your logic inside this.
}
Try using $("#mobile-view").is(":visible") == true
How can I check if a given DOM element is a a checkbox.
Scenario:
I have a set of textboxes and checkboxes in which the values are assigned dynamically. I don't have a way to identify if the DOM element is a checkbox or a textbox.
Using only vanilla javascript you could do
if (el.type && el.type === 'checkbox') {
...
}
or even shorter
if ((el || {}).type === 'checkbox') {
...
}
or in modern browsers you could use matches()
if (el.matches('[type="checkbox"]') {
...
}
If you're using jQuery, you can use the :checkbox pseudo-class selector along with is method:
if($("#that-particular-input").is(":checkbox")) {
}
Checks anything
function isCheckbox (element) {
return element instanceof HTMLInputElement
&& element.getAttribute('type') == 'checkbox'
}
if( $(element)[0].type == "checkbox" ) {
}
OR
if( $(element).is(':checkbox') ) {
}
Take a look at the checkbox selector.
var checkboxes = $("form input:checkbox");
You can tell what type an input is like this:
if ($(".your-input").is(":text"))
{
// Textbox
}
else if ($(".your-input").is(":checkbox"))
{
// Checkbox
}
if (<DOMNode>.type === "checkbox") {
// ...
}
Try this;
$(element).is(':checkbox');
here element is selector to your element
if( $(element).is(':checkbox') ) {
// do something
}
jQuery is():
if ($el.is(':checkbox')) { ... }
You can use the pseudo-selector :checkbox with a call to jQuery's is function:
$('#myinput').is(':checkbox')
You should have a decent naming convention which allows you to know if an element is a checkbox from just seeing it's id or name.
e.g. "chkMyCheckbox"
I need to find all block elements in a given node. Block elements are not just elements that have display:block in the CSS, but also default block elements like div and p.
I know I can just get computed style of the element and check for the display property, however, my code will execute in a long loop and getting computed styles flushes reflow stack every time, so it will be very expansive.
I'm looking for some trick to do this without getComputedStyle.
Edit
Here's my current code that I would like to improve:
var isBlockOrLineBreak = function(node)
{
if (!node) {
return false;
}
var nodeType = node.nodeType;
return nodeType == 1 && (!inlineDisplayRegex.test(getComputedStyleProperty(node, "display")) || node.tagName === "BR")
|| nodeType == 9 || nodeType == 11;
};
Another edit
jQuery's .css calls getComputedStyle under the hood. So that's not what I'm looking for.
My solution
Thanks everyone for suggestions. Unfortunately, none of them matched what I was looking for. After a lot of digging through documentation I realized that there's no real way to do this without getComputedStyle. However, I came up with the code that should avoid getComputedStyle as much as humanly possible. Here's the code:
$.extend($.expr[':'], {
block: function(a) {
var tagNames = {
"ADDRESS": true,"BLOCKQUOTE": true,"CENTER": true,"DIR": true,"DIV": true,
"DL": true,"FIELDSET": true,"FORM": true,"H1": true,"H2": true,"H3": true,
"H4": true,"H5": true,"H6": true,"HR": true,"ISINDEX": true,"MENU": true,
"NOFRAMES": true,"NOSCRIPT": true,"OL": true,"P": true,"PRE": true,"TABLE": true,
"UL": true,"DD": true,"DT": true,"FRAMESET": true,"LI": true,"TBODY": true,
"TD": true,"TFOOT": true,"TH": true,"THEAD": true,"TR": true
};
return $(a).is(function() {
if (tagNames[this.tagName.toUpperCase()]) {
if (this.style.display === "block")
{
return true;
}
if (this.style.display !== "" || this.style.float !== "")
{
return false;
}
else {
return $(this).css("display") === "block";
}
}
else {
if (this.style.display === "block") {
return
}
else {
return $(this).css("display") === "block";
}
}
});
}
});
Usage of this code is very simple just do $(":block") or $("form :block"). This will avoid using .css property in a lot of cases, and only fallback to it as a last resort.
Starx's answer was what gave me the idea to do this, so I'm going to mark his message as an answer.
For the answer to this problem, we take into account the universal CSS selector and the jQuery .filter() function:
$("*").filter(function(index) {
return $(this).css("display") == 'block';
});
This code looks at all elements it can find, and it returns a list of elements if they pass a filter. The element passes a filter if the filter function returns true for that element. In this case, the filter tests the display property of each found element and tests it against the desired value.
Now, you also mentioned that you want to find p and div elements. Luckily, we also have a way to find these in the filter function. Using jQuery's prop function, we can return a property of an element. In this case, we are interested in the tagName property of the DOM elements being filtered. Combining this feature with the above filter, we get:
$("*").filter(function(index) {
var $this = $(this);
var tagName = $this.prop("tagName").toLowerCase();
return $this.css("display") == 'block' || tagName == 'p' || tagName == 'div';
});
Notice how we set the tagName variable to lowercase, because we cannot expect a certain case for the tagName property (correct me if I'm wrong).
The best way I see is to
assign a common class to all the not-native block element and
using jQuery's mulitple-selector.
Then we can do it as simple as this this
CSS:
.block { display: block; }
jQuery:
var blockelements = $("div, p, table, ..., .block");
// ^ represents other block tags
If you want to include all the block elements. Here is a link
maybe this helps.
$('*').each( function(){
if ($(this).css("display") === "block")
$(this).css("background", "yellow") ;
});
jsfiddle