Finding if element is visible (JavaScript ) - javascript

I have a javascript function that tries to determine whether a div is visible and does various processes with that variable. I am successfully able to swap an elements visibility by changing it's display between none and block; but I cannot store this value...
I have tried getting the elements display attribute value and finding if the the element ID is visible but neither has worked. When I try .getAttribute it always returns null; I am not sure why because I know that id is defined and it has a display attribute.
Here is the code of the two different methods I have tried:
var myvar = $("#mydivID").is(":visible");
var myvar = document.getElementById("mydivID").getAttribute("display");
Any guidance or assistance would be greatly appreciated.

Try like this:
$(function () {
// Handler for .ready() called.
if ($("#mydivID").is(":visible")) {
alert('Element is visible');
}
});
FIDDLE
Please make sure to include the jQuery file inside the head tag, as follows
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>

If you would like to do this only javascript way you may try
window.getComputedStyle(document.getElementById("mydivID"),null).getPropertyValue('display')

Display is not an attribute, it's a CSS property inside the style attribute.
You may be looking for
var myvar = document.getElementById("mydivID").style.display;
or
var myvar = $("#mydivID").css('display');

Let's take a second to see what .is(":visible") is doing in jQuery, shall we?
Here's a link: https://github.com/jquery/jquery/blob/master/src/css.js#L529
return !jQuery.expr.filters.hidden( elem );
where
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
};
So, it's just checking the offset width and height of the element.
That said, and also worth noting, when jQuery checks to see if an element is hidden (i.e. like when triggering a 'toggle' event), it performs a check on the display property and its existence in the dom. https://github.com/jquery/jquery/blob/master/src/css.js#L43

var myvar = $("#mydivID").is(":visible"); //THis is JQUERY will return true if visible
var myvar = document.getElementById("mydivID").getAttribute("display"); //HERE Display is not a attribute so this will not give desired result.
MY SOLUTION
1.Select the element using QuerySelector
var myvar= document.querySelector('ELEMENT');
2.Check the OffsetWidth and Offsetheight to be greater than 0;
(myvar.offsetWidth > 0 || myvar.offsetHeight > 0)
3.if myvar is Greater than 0 then it's visble else not.

Related

jQuery UI - Select a class from the range slider

I'm currently using a jQuery UI range slider, which I'm trying to get the value of the "left" attribute of the minimum and maximum handler.
To do so, I have this javascript code used with the #price_range, in this case, everything works fine.
function GetLeftValue(){
var element = document.getElementById('price_range'),
left = element.getBoundingClientRect().left,
windowWidth = window.innerWidth;
var num = (Number(((left / windowWidth) * 100).toFixed(1))+ "%");
alert(num);
}
But when I'm trying to use it with the two handlers who have the following classes :
.ui-slider-handle .ui-corner-all .ui-state-default
I can't reach them using my js function with "getElementsByClassName()" of course :
var element = document.getElementsByClassName('class')
I tried every single one of the previous classes.
I also tried jQuery, related to my function, which i'm not really sure if it's a valid way to select elements :
var element = document.$('#slider-range > span:nth-child(2)') /*minimum handler*/
Finally, I thought that somehow, the element should be an id, so it can work properly, which I tried to add an Id to the previous classes:
$('.class').attr("id","myId");
Which is still failing to do what am I expecting.
Can anyone help me clear things up on this situation? Thanks.
Would something like this work for you?
let minvalue = $(".ui-slider-handle:eq(0)").css("left");
let maxvalue = $(".ui-slider-handle:eq(1)").css("left");
https://jsfiddle.net/sguk2a39/
EDIT: had some typos.

Move element into correct order based upon attribute value with jQuery

Im trying for the first time to use the data attibrute with jQuery, what id like to do is move an element to the correct order based upon the data-order attribute.
Im unsure how to find the correct value of the data-order attribute though as I keep recieveing 'undefined'?
an anybody see what im doing wrong? and also, is there a way to find the correct elemtn it should come after in the dom? so if the data-attribute for the current value is 5, then it should come after the attribute with the balue 4..
$(document).ready(function(){
// Move the profile back to positton funciton
function dmoveProfile(){
alert($(this).data("data-order"))
};
$('.box').click(function(){
alert($(this).data("data-order"))
});
// move into position
});
http://jsfiddle.net/Fta6p/
It seems as though you have enough answers as to why your ordering function doesn't work right.
Sorting your elements with basic JS is better. If you're looking for a jquery solution you can find it here:
function sortBoxes(){
for(var i=1; i<= $('.box').length; i++) {
var $box = $('.box[data-order="'+i+'"]');
$box.appendTo($('section'));
}
};
$('.box').click(function(){
// alert($(this).data("order"));
sortBoxes();
});
Demo: http://jsfiddle.net/Fta6p/7/
Solution #1:
.data() is used to Store arbitrary data associated with the matched elements. Use .attr() instead.
$('.box').click(function(){
alert($(this).attr("data-order"))
});
Updated Fiddle
Solution #2:
For Sorting the DOM elements in ascending order you can do like this:
jQuery.fn.sortDomElements = (function() {
return function(comparator) {
return Array.prototype.sort.call(this, comparator).each(function(i) {
this.parentNode.appendChild(this);
});
};
})();
$("section").children().sortDomElements(function(a,b){
akey = $(a).attr("data-order");
bkey = $(b).attr("data-order");
if (akey == bkey) return 0;
if (akey < bkey) return -1;
if (akey > bkey) return 1;
})
Fiddle Demo
Note: Your div #5 is overlapped on Div #1
You can see output of div normal, if you try inspect element you will or viewpagesource you will see the DOM elements are arranged in Ascending order
Updated fiddler
Use the jQuery .data() method without the "data-" prefix, like:
$(document).ready(function(){
// Move the profile back to positton funciton
function dmoveProfile(){
alert($(this).data("order"))
};
$('.box').click(function(){
alert($(this).data("order"))
});
// move into position
});

How to get the CSS left-property value of a div using JavaScript

My CSS rule looks like this:
#my-div{
display: none;
position: absolute;
left: -160px;
bottom: -150px;
}
I'm trying to get value of the left-property like this:
document.getElementById('my-div').style.left
document.getElementById('my-div').offsetLeft
The problem is that both return null. Where is the problem?
The problem is that someElement.style.left only work if you have inline style. Since you apply your styling through a stylesheet, you will not be able to fetch the value the way you expect.
You have a couple of other approaches you could take to get the value through JavaScript:
window.getComputedStyle:
It is possible to get the computed style of an element using window.getComputedStyle, the problem is that it has quite limited support (IE9+). If you still want to use it you could wrap it up in a function to make it a bit easier to get each property:
function getCssProperty(elmId, property){
var elem = document.getElementById(elmId);
return window.getComputedStyle(elem,null).getPropertyValue(property);
}
// You could now get your value like
var left = getCssProperty("my-div", "left");
Working example
jQuery (or some other library):
Another option would be to use a JavaScript library like jQuery (or whatever you prefer), which will provide you with a cross-browser solution to get the value.
With jQuery you could use the .css() method to read the CSS-property of the element.
$(function () {
var left = $("#my-div").css("left");
});
Working example
​
You should call this
document.getElementById('my-div').style.left
document.getElementById('my-div').offsetLeft
when document is loaded, if you call it earlier it will return null because element doesnt exists yet. So you can use jQuery to determine when all content is loaded.
$(function() {
//put your code here
});
The problem is that, since CSS is loaded separately from the JS, there's no official way to ensure that the style.left property will be accurate. The style.left property is a different, higher-priority style override.
You'll need to use the getComputedStyle function.
https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle
Ex:
var div = document.getElementById('my-div');
var style = getComputedStyle(div);
var left = style.getPropertyValue("left");
Maybe you have to call your functions after document ready.
If you use jQuery you can find left value faster:
$(document).ready(function() {
var $left = $('#my-div').css('left');
console.log($left);
});

How to live check element inset html with jQuery.

I have some block with dinamicly parsing content. I need to change some style for it but if there is some html. My question: is there any possible to live check with jQuery that some element have html at specify moment and set some actions if it's for example empty? Thx for some information.
My code:
if ($('.degrees').live().html === ("")){
$('.block').fadeOut('slow');
}
Try this:
to detect divs that were empty and got their html changed:
$('.degrees:empty').on('DOMSubtreeModified',function(){
//...
});
to detect every html change
$('.degrees').on('DOMSubtreeModified',function(){
if($(this).is(':empty')) // check if it became empty ..
});
You can check it this way:
if($('.degrees').html().length > 0){
// element has children
} else {
// no children
}
You can check if the element is empty like so:
if ($('.degrees').is(':empty')){
$('.block').fadeOut('slow');
}
but it will only work when you do the check, and not for future elements, to do that you would have to use an interval to check it regularly, and that's generally not a good idea.
You can check the children element:
var $main = $('.degrees'),
$child = $('.block');
if($main.children().length < 0) {
$child.fadeOut(500);
}

Check if element legally supports the src attribute or innerHTML

Is there a way to check whether an element can display innerHTML or $.html() (like elems that have a separate closing tag) OR is an element whose is meant to have a src attribute according to the HTML spec such as <img>? I'm looking for fast/reliable way to do this via jQuery or native JavaScript.
Edit: According to the HTML spec, elements not designed to have inner content are called void elements but there are also elements like this <iframe src=url>inner</iframe> that are totally valid.
Unfortunately, there isn't a foolproof way to do this because in Javascript, any element can have those attributes.
Also, as odd at it may seem, almost all HTML elements, including <img>, have an innerHTML attribute, even though it can't really use it!
Your best bet is to make a table that specifies what elements have what.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
</style>
</head>
<body>
<div id="anElementWithInnerHTML"></div>
<img id="anElementWithInnerSRC" />
<script>
var div = document.getElementById("anElementWithInnerHTML");
console.log(div.innerHTML); //Outputs ""
console.log(div.src); //Outputs undefined
var img = document.getElementById("anElementWithInnerSRC");
console.log(img.innerHTML); //Outputs "" (weird right?)
console.log(img.src); //Outputs ""
</script>
</body>
</html>
I suppose you could do
if (typeof element.src !== 'undefined')
if (element.innerHTML ...)
Not totally reliable since any element could add those properties (JSON).
(thanks for the typeof fix, thief)
I found the list of elements that (according to the spec) allow the src attribute:
audio, embed, iframe, img, input, script, source, track, video
So this works to check by name:
function srcAllowed(tag) {
if ( !tag ) { return false; }
var tags = ['audio','embed','iframe','img','input','script','source','track','video'];
return 0 <= $.inArray(tag.toLowerCase(), tags); // boolean
}
This works for getting the appropriate content:
function getContent(elem) {
// #param elem is a selected element like $(this)
// returns empty string if attr() and html() are both are falsey
return elem.attr('src') || elem.html();
}
And this is even safer:
function getContentSafer(elem) {
// #param elem is a selected element like $(this)
// returns empty string if attr() and html() are both are falsey
return srcAllowed(elem.prop('tagName')) ? (elem.attr('src') || elem.html()) : elem.html();
}

Categories