Wrong ClientRect height when image inside targeted element - javascript

I have simple html:
<a href='#' id='target'>
<img src='https://sftextures.com/texture/6485/0/6487/metal-dots-very-dark-grey-black-solid-material-seamless-texture-256x256.jpg'/>
</a>
I want to get the height of the #target element which should basically copy the image:
let target = document.getElementById('target');
let height = target.getBoundingClientRect().height;
// result 18px, image size is 256px
Why the target a link element does not copy the height of the child? Let's say my site has thousands of elements and I can't identify children. How could I get correct height in similar cases where it does not match the real height?
https://jsfiddle.net/b2y8gtLx/

If you have more elements, try setting a <div> as parent. Should work fine.

with making display to 'inline-block'
target.onclick = function () // just to take care of image loading delay
{
target.style.display = 'inline-block';
targetHeight.textContent = `parent height: ${target.getBoundingClientRect().height} px `;
image_Height.textContent = `img height: ${ImgInsideA.getBoundingClientRect().height} px `;
target.style.display = null;
console.log( target.getBoundingClientRect().height );
}
<a href='#' id='target'>
<img id="ImgInsideA"
src='https://sftextures.com/texture/6485/0/6487/metal-dots-very-dark-grey-black-solid-material-seamless-texture-256x256.jpg' />
</a>
<div id='targetHeight'> -- </div>
<div id='image_Height'> -- </div>

let height = target.offsetHeight.
Please try it. It is working

Related

How can i change div position by javascript

Is possible to change div position like( absolute or relative by css) but use java script
Code for example
<div id="podpis" margin-top="2">
<div class="invoice-signature">
<span><?=$xml->sanitize($invoice['Invoice']['user_name'])?></span><br/>
<span>First name and second name osoby uprawnionej do wystawiania faktury</span>
</div>
<div class="invoice-signature">
<span><br/></span><br/>
<span>First name and second name</span>
</div>
<div clear="both"/>
</div>
I want change position of div id="podpis".
Thank you for your answers!
To set the position value:
document.getElementById('podpis').style.position = 'relative';
or
document.getElementById('podpis').style.position = 'absolute';
And based on your comments it sounds to me like you want to have the podpis stay at the bottom of the page no matter what?
//div stays in same place on screen no matter what, even when scrolling
document.getElementById('podpis').style.position = 'fixed';
//div goes to the bottom of the page
document.getElementById('podpis').style.bottom = '0';
Yes you could using :
<script>
document.getElementById('podpis').style.position = 'absolute';
document.getElementById('podpis').style.position = 'relative';
</script>
Hope this helps.

Html in-page hidden text that isn't shown until link is clicked

sort of new to html. I'm looking to create animation that when am image is clicked, it plays an animation that splits open a half page of text and in stuff. Something like this: http://sketchtoy.com/62368639
If you want to do things like that, you should really have a look at a javascript framework like jquery (www.jquery.com)
I find this one particularly easy to learn.
For what you want to do:
<div style="display: none;" id="mytext">Your text</div>
<a onclick="$('#mytext').show()"></a>
The basic process is
Add the click handler for the images
Find the last image in the row that the clicked image is in
set the contents of the expanding element
insert the expanding element after the image from step 2
show the expanding element (in this case a slideDown animation)
This is using jQuery library, which you did not tag, but it makes doing this a lot easier. If you need a vanilla javascript approach one can be added.
HTML
<div id="container">
<img src="http://placehold.it/128x128" />
<img src="http://placehold.it/128x128" />
<img src="http://placehold.it/128x128" />
<img src="http://placehold.it/128x64" />
<img src="http://placehold.it/128x64" />
<img src="http://placehold.it/128x64" />
<div id="expander">
<img src="" />
<div id="info">
some info
</div>
</div>
</div>
JS
//Just making the expander half the height of the viewport
var winheight = $(window).height();
$("#expander").css("height",winheight/2);
$("img").click(function(){
var img = $(this);
var src = img.attr("src");
var afterImg = findLastImgInRow(img);
var expander = $("#expander");
//Hide the expander if previously open
expander.hide(0);
//just setting the insides
expander.find("img").attr("src",src);
expander.find("#info").html("This is a test");
//Put the expander after the last image in the row
//so it will appear between its row and the next
expander.insertAfter(afterImg);
expander.slideDown(600);
//This scrolls the page so that it will make the
//expander appear in the middle of the page
$('html, body').animate({
scrollTop: expander.offset().top-(winheight/4)
}, 600);
});
//Function to find the last image
//in a row by comparing their offset top values
function findLastImgInRow(img){
var imgTop = img.offset().top;
var img2 = img;
do{
if( img2.offset().top != imgTop ){
img2 = img2.prev();
break;
}
}while(img2=img2.next());
return img2;
}
JSFiddle Demo

Div Inner Content width

I have a div structure as follows:
<div id="showHide">
<div>Alarm</div>
<div>Alarmasdf</div>
<div>Alarmasdffasdff</div>
Is there any way that I can get the width of the content like (Alarmasdffasdff). This content is the largest.
I am able to get the length of the content, but not the width.
Please suggest.
Assuming the div elements have been changed to display: inline, the width of the element will match the content.
If this is not the case I would suggest wrapping the content in a span, or any other suitable inline element, and getting the width of that. For example:
<div id="showHide">
<div>
<span>Alarm</span>
</div>
<div>
<span>Alarmasdf</span>
</div>
<div>
<span>Alarmasdffasdff</span>
</div>
</div>
$('#showhide').find('div:last span').width();
The Width of all of your 'div's is 100% regardless of their content. This is how block level elements behave...
use :contains()
$( "#showhide div:contains('Alarmasdffasdff')").width();
As said by others, width of a block level element is 100% regardless of its content's width. So first you need to change the display of the div to inline-block
<style>
#showHide div
{
display:inline-block;
}
</style>
<div id="showHide">
<div>Alarm
</div>
<div>Alarmasdf
</div>
<div>Alarmasdffasdff
</div>
</div>
$('#showhide>div:contains("Alarmasdffasdff")').innerWidth();
Jquery makes it very easy.
$('#showHide').find('div:last').css('width');
css() returns the computed style of the element, which is the inline styling as well as default styling and any other css selector.
Without jquery it goes a little less "clean"
var mystyle = window.getComputedStyle ? window.getComputedStyle(myobject, null) : myobject.currentStyle;
mystyle.width shows the calculated width, where myobject is the element you want to check.
html :
<div id="showHide">
<div>Alarm</div>
<div>Alarmasdf</div>
<div>Alarmasdffasdff</div>
</div>
script :
var lastDiv = $('#showHide').find('div').last();
var lastDivWidth = lastDiv.width();
alert(lastDivWidth);
jsFiddle
<div id="showHide">
<div class="content" style="width:50px" >Alarm</div>
<div class="content" style="width:60px">Alarmasdf</div>
<div class="content" style="width:120px">Alarmasdffasdff</div>
</div>
Custom width is given so that u can understand the difference, else every div will be having same width, and class content is added for convinience of processing
findWidth("Alarmasdf"); // Calls the function below
function findWidth(value)
{
var width=0;
$(".content").each(function(e){
if($(this).text()==value)
{
width = $(this).width();
}
});
alert(width);
}
Check the fiddle here
http://jsfiddle.net/46LH9/

count number of style tags in div container

I'm trying to count the total number of img elements and then the number of style tags present in a parent div tag using jquery. The current HTML looks like this:
<div id="origin" class="ui-test">
<div class="polaroid ui-test">
<img src="http://example.com/84655/l/72105d6f46205a948f00f6e59c299930.jpg" >
</div>
<div class="polaroid ui-test">
<img src="http://example.com/77676/l/819e2093be4c61d2e21b1175f9d0f0f9.jpg" >
</div>
<div class="polaroid ui-test" style="left: 288.328125px; top: -8px; display: none;">
<img src="http://example.com/47901/l/79f936ef9847793254bad21e16b2448f.jpg" >
</div>
<div class="polaroid ui-test" style="left: 94.328125px; top: 6px; display: none;">
<img src="http://example.com/49761/l/6d10064d6b189c6934fd264ac295f5f8.jpg" >
</div>
</div>
Based on the above example I'm trying to get a count of total img elements under the parent origin container and then how many are showing display: none;
I would expect to see: 4 img tags total and 2 hidden img tags
I think I can get the toital number of images with the following:
var totalImages = $("#origin img").length;
How do I get the total number of images showing display:none?
Try this:
var totalImages = $("#origin img").length;
var totalImagesWithStyle = $("#origin div[style] img").length;
//or
var totalImagesWithStyle = $("#origin div:hidden img").length;
//or
var totalImagesWithStyle = $("#origin .polaroid:hidden img").length;
Fiddle
Try using the :hidden jQuery selector.
$('#origin img:hidden');
See http://jsfiddle.net/35uvZ/. It consists of your HTML part; I left the left and top declarations. Other than that just some jQuery:
var $imgWrp = $('#origin .polaroid');
var $images = $imgWrp.find('img');
var $hiddenImages = $imgWrp.filter(':hidden').find('img');
console.log($images.length);
console.log($hiddenImages.length);
The :hidden selector selects all elements that are hidden.
$( "#origin div:hidden" ).length;
For efficiency, I would break it up into two steps:
var allImages = $("#origin").find("img");
var hiddenImages = allImages.filter(":hidden");
Then you could retrieve the lengths of either or both sets (as needed) and proceed from there.

Run script for each div with the same class

Well, I'm running ISOTOPE. So I have to set the DIV's height and width through jQuery. It's a photographer's portfolio, so I have thousand of photos with different sizes.
HTML
<div class="element metal cesco1 " data-symbol="Hg" data-category="transition">
<span>
<a class="fancybox" href="fotos/full/full01.png" data-fancybox-group="gallery">
<img src="fotos/thumbs/thumb01.png"/>
</a>
</span>
</div>
<div class="element metal cesco1 " data-symbol="Hg" data-category="transition">
<span>
<a class="fancybox" href="fotos/full/full03.png" data-fancybox-group="gallery">
<img src="fotos/thumbs/thumb03.png"/>
</a>
</span>
</div>
JavaScript:
<script type="text/javascript">
var width = 0;
$('.cesco1 img').each(function() {
width += $(this).outerWidth( true );
alert(width);
});
$('.cesco1').css('width', width + 0);
</script>
I'm using the same JavaScript for height as well.
The first thumb width is 300px and the second is 200px.
So I get the a 500px width div.it adds up.
I would like to set the width for each DIV at the time.
I'm a newbie, sorry if it's dumb.
Use the .closest() method to access the DIV that contains the image.
$('.cesco1 img').each(function() {
width += $(this).outerWidth( true );
alert(width);
$(this).closest('.cesco1').css('width', width);
});
If the image is always an immediate child of the DIV, you can use the more efficient selector .cesco1 > img and .parent() instead of .closest('.cesco1').
Try this:
<script type="text/javascript">
$(function(){
$('.cesco1').each(function() {
var width = 0;
$(this).children('img').each(function(){
width += $(this).outerWidth( true ); // reset the width
});
$(this).css('width', width);
});
});
</script>

Categories