I am currently working on determining whether a child element is visible within its parent element. To achieve this, I am comparing the width of the parent element to the position of the child element using position().left
.
Given that I have multiple distinct parent and child elements, I am utilizing each
functions.
//Iterating over each p element in the Instagram feed
jQuery('#instagram-feed .meta-data p').each(function(){
// Storing the width of this p element
var parentWidth = jQuery(this).width();
// Iterating over each a element within this p
jQuery(this).children('a').each(function(){
// Comparing the width of the p element with the position of this a element
if(parentWidth < jQuery(this).position().left) {
// Changing text color to green if position exceeds width
jQuery(this).css('color', 'green');
console.log("Not inside element");
} else {
// Changing text color to red if position is within width
jQuery(this).css('color', 'red');
console.log("Inside element");
}
console.log(jQuery(this).position().left);
});
});
I've created a fiddle for you to visualize and test: http://jsfiddle.net/fprm7mgd/9/ (Ensure the three elements are positioned horizontally to observe the "bug")
https://i.stack.imgur.com/Ah9c2.png
The issue arises in the third parent element where it appears that position().left
is calculated from the first or higher-level parent element. Why does the link in the third parent turn green? It should be red since it's contained within the parent... What mistake have I made?