Javascript image height and other calculation - javascript

I was having a problem on getting the height and also calculating other calculations.
I want to get the image height after it has loaded, so I put it on the onload attribute of <img></img> function, here's my code
<p class="test1" style="position:absolute;bottom:0px;">
<img src="'+getBaseURL()+'js/check/no-image.png" rel="fullname"
onload="verticalCenter()"/>
</p>
function verticalCenter(){
var imageHeight = jQuery(".test1 img").height(); //I get a result of 0
var total = imageHeight / 2 + 80
}
I already tried using setTimeout but it still fails.
What I was planning to do here is to set the css of <p class="test1"> into like this:
jQuery(".test1").css("bottom","-"+total);
As I said, this isn't working because I don't get a result in total.
How would I do this, Is there a way to solve this problems, I'm already scratching my head on this.
Thanks in advance!

$(window).load(function () {
var imageHeight = jQuery(".test1 img").height(); //I get a result of 0
var total = imageHeight / 2 + 80
}
<p class="test1" style="position:absolute;bottom:0px;">
<img src="'+getBaseURL()+'js/check/no-image.png" rel="fullname"/>
</p>

You need units on CSS dimensions.
jQuery(".test1").css("bottom","-"+total+"px");
You should also check to make sure that total is the value you are expecting it to be before setting it.
http://jsfiddle.net/jfriend00/yHqr7/

It might be easier to set all the image heights when the form is ready:
$(document).ready(
$('p.text1 img').each(verticalCenter);
)
Unless you're using ajax to load the images; if that is the case, then you should use the live() event:
$('p.text1 img').live(verticalCenter);
Then in your function you can set everything:
function verticalCenter(){
$(this).css('bottom',"-" + ($(this).height() / 2 + 80) + 'px');
}

Related

Position image randomly after each onclick event (image must be in div tag)

So I am very new (as I am sure my code shows :P) and I must create code that contains an image in a div tag. It must be this way. Once the document is opened the image(div) is to be displayed at a random position. Each time the image(div) is clicked, the image alone moves to another random position. It does not replicate itself. Just moves. I have had other "better" attempts but with all my editing and changing all I get is the image in the top left corner.
I tried numerous things that all failed to work. Obviously failed because the code was terrible.
I have tried a variation of onclick events etc...I know many errors are visible. This is not one of those instances where I believe the logic is sound and it should work. This is a "what am I at" instance
<script>
function fpos () {
var img = document.getElementById('myImage') //is this needed at all?
var x = Math.floor(Math.random()*600);
var y = Math.floor(Math.random()*600);
var z = Math.floor(Math.random()*600);
}
function rmove() {
img.style.top = x + 'px';
img.style.left = y + 'px';
}
</script>
</head>
<body onload="fpos">
<div style = position:absolute; onclick="rmove" >
<img id="myImage" src='images/iasip.jpeg'> </img>
</div>
</body>
So, first, don't take this the wrong way my man but you gotta post some code to show us what you're working with. Makes all the difference for troubleshooting.
That said, you're gonna need to do with with JS. First target the image element. Can use querySelector to hit either the class or id or just getElementById.
Then add an event listener to render it at a random coordinate. Like this.
<div id="imageContainer">
<img src="your-image-source" alt="your-image-description">
</div>
<script>
// get the image container element
var imageContainer = document.getElementById("imageContainer");
// set the initial random position for the image container
imageContainer.style.left = Math.floor(Math.random() * window.innerWidth) + "px";
imageContainer.style.top = Math.floor(Math.random() * window.innerHeight) + "px";
// when the image container is clicked, set a new random position
imageContainer.addEventListener("click", function() {
imageContainer.style.left = Math.floor(Math.random() * window.innerWidth) + "px";
imageContainer.style.top = Math.floor(Math.random() * window.innerHeight) + "px";
});
</script>
Can either do that inline like in the example or add it to your script file.
Here is a working example I just threw together.
Basically you need to create a function that moves the image each time by calculating a random number for the height and width and then multiplying by the size of the window so that number can span the full width/length of the screen.
Then you can add 'px' to the end of the calculation to use pixels as the unit and set that to the left and top properties of the image to move it that far from the left and top of the screen using absolute position (coordinates).
window.onload = function() {
move()
}
function move() {
let img = document.getElementById('logo')
img.style.left = Math.floor(Math.random() * window.innerWidth) + "px"
img.style.top = Math.floor(Math.random() * window.innerHeight) + "px"
}
#logo {
height: 100px;
position: absolute;
}
<div>
<img onclick='move()' id='logo' src='https://upload.wikimedia.org/wikipedia/commons/thumb/2/24/LEGO_logo.svg/2048px-LEGO_logo.svg.png' />
</div>
Don't worry, try to isolate some code so we can review it.
Once the document is opened the image(div) is to be displayed at a
random position.
By inspecting an element's properties with Right Click > Inspect > Property you'll find all javascript properties that you have access to once you select the element with a selector (document.querySelector for example)
Try something with that, i think that the easiest way is to use
element.style.transform = "translate(x,y)"
like x.style.transform = "translate(10px, 20px)";

Javascript set a variable that changes on each child item

This may seem like an easily answered question but it's one I've been struggling for a little while.
Let me first explain what I'm trying to achieve.
I have a gallery of images and I want each of the images to centered vertically inside their container. The images are of varying shapes, sizes and aspect ratios so my code needs to be variable for each image therein. Here is what I have so far:
<div id="cbp-fwslider" class="cbp-fwslider">
<img src="images/large/1.jpg" alt="img01"/>
<img src="images/large/2.jpg" alt="img02"/>
<img src="images/large/3.jpg" alt="img03"/>
</div>
And here is my javascript:
var $img = $('div#cbp-fwslider img');
var ih = $img.height();
var $div = $('div#cbp-fwslider');
var dh = $div.height();
if (dh > ih) {
var dif = (dh - ih);
$img.css('margin-top', + dif / 2 + "px");
}
Now, this works in part. What it does is calculates the correct "margin-top" to vertically center the first image within the container but then applies it to all involved. I have no doubt that this is because I have set the javascript to set the "margin-top" as the same for all the images.
My question is, how do I set a variable to make it so it does this separately for all the items that I put in my gallery?
Forgive me if this is a basic question that I could have found the answer for elsewhere, I am pretty wet behind the ears when it comes to javascript.
Also if anybody knows of an easier/more efficient way of achieving what I want then it would be great if you could point me in the right direction.
I must advise that the container has a dynamic height and so do all images. With the nature of how the gallery works, I can't use absolute positioning and THIS technique doesn't seem to work either.
Thanks in advance for any help.
You'll want to run your code individually on each image rather than on the collection of images. You can do this by using each to loop through the collection:
$('div#cbp-fwslider img').each(function(){
var $img = $(this);
var ih = $img.height();
var $div = $('div#cbp-fwslider');
var dh = $div.height();
if (dh > ih) {
var dif = (dh - ih);
$img.css('margin-top', + dif / 2 + "px");
}
});
You can just use css to vertically align all images to center.
<div id="cbp-fwslider" class="cbp-fwslider">
<img src="images/large/1.jpg" alt="img01"/>
<img src="images/large/2.jpg" alt="img02"/>
<img src="images/large/3.jpg" alt="img03"/>
</div>
css
img {
vertical-align: middle;
}​
see http://jsfiddle.net/vishnurajv/xR28t/
Try to find the maximum height of img in your div, after that set margin-top for all of other img. This is my idea, you or someone can do better.
var maxHeight = 0;
$('div#cbp-fwslider img').each(function(){
if($(this).height() > maxHeight) maxHeight = $(this).height();
});
$('div#cbp-fwslider img').each(function(){
$(this).css('margin-top', Number(maxHeight - $(this).height()) / 2 + 'px');
});
Hope help!

how to get the attribute value of 'width' property

This is my progress bar http://jsfiddle.net/vjNpj/2247/ , I want the span (percentage value) can change together when the width of the div changed. like when the width is 50%, the span will display 50%..
what I can think of is attr(), but how to get its value?
I tried this but not working
var percent = $('#progressbar > div').attr('width');
alert(percent);
Lets understand this first
The difference between .css(width) and .width() is that the latter
returns a unit-less pixel value (for example, 400) while the former
returns a value with units intact (for example, 400px). The .width()
method is recommended when an element's width needs to be used in a
mathematical calculation.
So you can do,
alert($('#progressbar > div').css("width")); // 388
alert($('#progressbar > div').prop("width")); // 388px;
Fiddle for more understanding
Here is a JSFIDDLE that achieves what you are after
$progress_bar = $('#progressbar');
var progressbar_width = Math.floor(100 * ($progress_bar.find('div').width()) / $progress_bar.width())
$progress_bar.find('span').text(progressbar_width + '%')
You will have to call this code everytime you update the width of the progress bar.
var percent = $('#progressbar > div').width();
or
var percent = $('#progressbar > div').css('width');
alert(percent);
demo
Hey width is an attribute just like value is an attribute, so you may only want to get width not value of width.And for that I recommend answer by amit aggarwal.
You need to do some mathematical calculation for this work -
var percent = $('#progressbar div').width();
var Percent_Load = parseInt((percent * 100)/ $('#progressbar').width(), 10)
alert(Percent_Load);
Try This

document.getElementById(); does not work for third time

Determine Minheight and put it via javascript. It work successfully twice but same code is not working in third calling. This one (document.getElementById("rightadmin").style.minHeight=wrapHeight+'px';) is not working. More amazing is that if I make the 3rd one elevate to 2nd position then it works and then 3rd one not working. So basically whatever I put after 2nd one don't work.
JavaScript:
function height(){
var dheight= ($(document).height());
var wheight= ($(window).height());
if(dheight>wheight){
var wrapHeight= dheight;
}
else {
var wrapHeight=wheight;
}
document.getElementById("iframeArea").style.minHeight=wrapHeight+'px';
document.getElementById("dailySchedule").style.minHeight=wrapHeight+'px';
document.getElementById("rightadmin").style.minHeight=wrapHeight+'px';
}
html:
<body onload="height();">
<!--Start of iframeArea-->
<div class="iframeArea" id="iframeArea">
<div class="btnRight" id="rightadmin">
</div>
<!--End of btnRight-->
</div>
<!--End of iframeArea-->
Are you sure the dailySchedule id exists ? If not your function will throw an error and won't execute the last line.
Might be due to scope problems - the variable wrapHeight is local in two blocks.
Should not have any effect on the outcome, but this code is more elegant way to assign the third variable:
var dheight = $(document).height();
var wheight = $(window).height();
var wrapHeight = (dheight > wheight) ? dheight : wheight;
As all others already said, something else is the problem.
I don't see element with id=dailySchedule on the page. If no element with that id is on the page you should get an error. Check browser console for javascript error.
you say <body onload='height()'> and never check if the document is ready, and then there is perhaps no div with id rightadmin...
Try to convert to jQuery and do something like this and delete the onload attribute.
$(document).ready(function(){
//your code here
}
I am using now the following code. It works fine for everything.
$(function(){
var dheight= ($(document).height());
var wheight= ($(window).height());
var wrapHeight = (dheight > wheight) ? dheight : wheight;
$('.dailySchedule').css({ "min-height": wrapHeight + 'px' });
$('.iframeArea').css({ "min-height": wrapHeight + 'px' });
$('.btnRight').css({ "min-height": wrapHeight + 'px' });
});
Thanks for answeri

Looping a dynamic text sizing function jquery/javascript

I'm trying to dynamicly resize text within a div so that the text does not run outside of the box it was intended for. I'm trying to do this so that I can make a printable form.
Geeky Monkey has a jquery plugin that works great but my problem is I can't loop it to do it over and over for different div's to make sure they're all properly sized. If I make all my div's the same class they all get the same text size so obviously this doesn't work.
This is Geeky Monkey's unedited code
(function($) {
$.fn.textfill = function(options) {
var fontSize = options.maxFontPixels;
var ourText = $('span:visible:first', this);
var maxHeight = $(this).height();
var maxWidth = $(this).width();
var textHeight;
var textWidth;
do {
ourText.css('font-size', fontSize);
textHeight = ourText.height();
textWidth = ourText.width();
fontSize = fontSize - 1;
} while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
return this;
}
})(jQuery);
$(document).ready(function() {
$('.jtextfill').textfill({ maxFontPixels: 36 });
});
And the html code that goes with it
<div class='jtextfill' style='width:100px;height:50px;'>
<span>My Text Here</span>
</div>
This is what I tried to do to change it and make it a loop
$(document).ready(
for(i=1;i<3;i++){
function() {
$('.jtextfill' + i).textfill({ maxFontPixels: 72 });
})};
And the html to go with my revision
<div class='jtextfill1' style='width:400px;height:200px;'>
<span>THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG</span>
</div>
<div class='jtextfill2' style='width:50px;height:25px;'>
<span>THIS IS THE SECOND PART OF MY TEXT</span>
</div>
As I'm sure you could guess it's not working. jquery does still confuse me so please forgive me if it is an obvious mistake. Any help would be greatly appreciated.
Thanks
OK, as I understand it you want to have various divs each with a different class so that you can give each its own font size (and potentially other individual properties). You want to be able to process each div to - if necessary - shrink the font of the span in the div so that it will fit in the div without overflowing.
If so, calling the textfill() method in a loop but passing the same maxFontPixels parameter to it for every div won't work, because obviously they'll all then start out with the same default maximum font size. You could update your loop to pass in different font sizes, but instead I would suggest changing the textfill() to start with the current font-size of the div, rather than taking it as a parameter.
Then, rather than trying to do a loop to repeatedly call textfill(), you can use a single JQuery selector that selects all of the divs you want to process. Following is just one way to do what I've described. (Note: I haven't actually tested it, but I hope it will get you on your way.)
EDIT: In the original code there was also a basic problem with the .textfill plugin, that (as with any JQuery plugin) its this was a JQuery object that - depending on the selector - may be a list of many DOM elements, but it was treating it as a single DOM element. Just needed to add a this.each() loop around the rest of the function code and it works.
<style>
.someclass1 { font-size: 36px; }
.someclass2 { font-size: 48px; }
</style>
<div class='someclass1 jtextfill' style='width:400px;height:200px;overflow:hidden;'>
<span>THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG</span>
</div>
<div class='someclass2 jtextfill' style='width:50px;height:25px;overflow:hidden;'>
<span>THIS IS THE SECOND PART OF MY TEXT</span>
</div>
<script>
(function($) {
$.fn.textfill = function() {
// EDIT: added the .each()
this.each(function() {
var fontSize = parseInt($(this).css('font-size'),10);
var ourText = $('span:visible:first', this);
var maxHeight = $(this).height();
var maxWidth = $(this).width();
var textHeight;
var textWidth;
do {
ourText.css('font-size', fontSize + "px");
textHeight = ourText.height();
textWidth = ourText.width();
fontSize = fontSize - 1;
} while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
// EDIT: added the closing brackets for the .each
});
return this;
}
})(jQuery);
$(document).ready(function() {
$('.jtextfill').textfill();
});
</script>
Notes: in this case the 'jtextfill' class isn't actually defined in the stylesheet, it is used solely as a convenient way to let JQuery select all of the divs that you want to process. The actual font stylings are applied via the 'someClass1', etc., classes. (In case you weren't aware, HTML/CSS allows you to apply multiple classes to the same element.)
I've changed only twothree things in the textfill() method: (1) I get the font-size from the element, which should be returned as a string like '36px', then use parseInt to grab the integer part of that (throwing away the 'px'). (2) When the font is set inside the loop I append 'px' back onto the font size. (3) Added a .each() loop within the plugin function.

Categories

Resources