Javascript - how to call function correctly - javascript

I don't really understand how to call a Javascript function properly on document ready. My goal is to resize a div depending on the height of browser window, and I took this code from another answer on SO. What am I doing wrong?
function resizeElementHeight(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}
$(document).ready(resizeElementHeight($('#global_image')));
The element I am trying to call has the id "global_image", but I get "cannot set property height of undefined", and I feel lost in how to providing the right element to the function. Thanks for your help!

ready() expects a function as its argument. Right now, you are calling resizeElementHeight() and passing its return value to ready().
In your current code, at the point of calling resizeElementHeight() the DOM is not yet ready and the element #global_image is not yet in the DOM tree.
You should change it to:
$(document).ready(function() {
resizeElementHeight($('#global_image'));
});

The function resizeElementHeight expects a DOM-element, not a JavaScript object. To expand on techfoobar's answer you should change it to:
$(document).ready(function() {
resizeElementHeight($('#global_image')[0]);
});

the DOM object is not completely loaded when you call resizeElementHeight.replace by is:
$(document).ready(function() {
resizeElementHeight($('#global_image')[0]);
});

Related

How do I operate with the width on a jQuery click event?

I am creating a function that each time it is called 1px is subtracted to the width of an image. I can't figure it out...
Something like this:
var leafCompress = function(){
.css("width" -1 + "px"); //This line is definitely wrong
}
(The following code is working) Here I'm adding the event listener so on each click it calls the leafCompress function.
leaf.on("click",function(){
leafCompress();
});
the problem comes from your function leafCompress
$( "#panda" ).on('click', () => {
resize();
});
const resize = () => {
let width = $("#panda").width() - 50; // get the width of the image and substract 50
$("#panda").css("width", width);
}
#panda {
width: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="panda" src="http://r.ddmcdn.com/w_624/s_f/o_1/cx_0/cy_17/cw_624/ch_416/APL/uploads/2014/06/red-panda-09-625x350.jpg" />
I am not sure if you are using jQuery but, you can do it with jQuery .width function,
the css('width') function returns the width as string i.e: "780px" and to use it to set the width property you usually do .css('width', valueToBeSet)
However you can achieve the same result using jQuery .width function
$().width() will return the actual width and $().width(value) will set width as the value
The most trivial way:
leaf.click(function(){
var node = $(this);
node.css('width', node.width() - 1 + 'px');
})
If event handler is a function, "this" points to event target.

Vue.js style working on wrong element

It's really strange.
I'm making floating sidebar in the Vue component, so need to change the css position value between fixed and relative.
so what I did is giving an ID for the sidebar element, and on scroll event, check the position on the page and changed some css values.
Here is my code.
created() {
document.addEventListener('scroll', this.handleScroll);
},
destroyed() {
document.addEventListener('scroll', this.handleScroll);
}
/* ... */
handleScroll(e) {
var doc = document.documentElement;
var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
var originWidth = $("#fields-to-move").width() + 2;
if(this.screen_no == 2){
if (280 <= top) {
document.getElementById("fields-to-move").style.position = "fixed";
document.getElementById("fields-to-move").style.top = 10 + 'px' ;
document.getElementById("fields-to-move").style.width = originWidth + 'px';
} else {
document.getElementById("fields-to-move").style.position = "relative";
document.getElementById("fields-to-move").style.top = 'auto' ;
document.getElementById("fields-to-move").style.width = originWidth + 'px';
}
}
}
"fields-to-move" is the ID of DOM element I'm going to change css.
It's working well.
But the problem is that above css ( position: fixed, top:10px and width) also applied on other element without the ID.
There's one thing more need to mention.
The element with the ID is a child element of another one which is mounted with v-if condition.
After the parent element dismounted, the css is applied to the wrong element that's mounted after it.
I'm not sure my explanation is enough. Please let me know if you have any questions above my problem.
Thanks in advance.
If you can provide separeted example in jsfiddle it would be easier to help...
But I belive that this behaviour can caused by some Vue optimizations described here: documentation
edit:
Try to execute entire logic of "handleScroll" in vues nextTick.

Why is this function not having the intended behavior on page load?

I have a function that I'm using to make a bunch of sibling divs have the same height. When the DOM is ready, I define it, call it, and then set it to be called whenever the window is resized.
jQuery(function($){
function rescaleStuff ( )
{
$('.children-have-equal-height').each(function(){
var children = $(this).children();
var numChildren = children.length;
if (numChildren > 1)
{
var firstChild = children.first();
var maxHeight = firstChild.height();
firstChild.siblings().each(function() {
var thisHeight = $(this).height();
if (thisHeight > maxHeight)
maxHeight = thisHeight;
});
children.height(maxHeight);
}
});
}
rescaleStuff();
$(window).resize(function()
{
rescaleStuff();
});
});
The function rescaleStuff is working awesomely when it is invoked by the resizing of the window, but it is not working correctly when the page loads. For some reason, it is calculating the heights as smaller than the actual heights. Why is that?
Also, it is possible to make my procedure any more compact, elegant, readable, efficient, clever and maintainable? I didn't think so. ;)
Use:
$( window ).load(function() {
....
});
If you have to calculate widths/heights, positions... ready() method is not sufficient. You have to wait until whole content (with images) is loaded, since content affect heights and widths.

How to change the height of div with the content of other div

I have two div in my website page one beside the other(one left and one right),I want to change the height of the left one with the content of the right one using javascript
I tried to have the dynamic height of the right div :
function getHeight() {
var doc = document.getElementById('div.right');
if (document.all) // ok I.E
{
H = doc.currentStyle.height;
}
else // ok FF
{
H = document.defaultView.getComputedStyle(doc, null).height;
}
}​
But I stopped here because I don't know how to pass the javascript variable to my page of style CSS,I mean I dont know how to apply this value in the other div(left div) in the same page automatically.
Any Idea?
Just use
document.getElementById('div.left').style.height = H;
Edit
AFAIK you cant modify an external stylesheet from javascript
Is the height of the div determined at the time the document is served, loaded or or any arbitrary time after the document has loaded?
The code I suggested above was to be used like this(I'm assuming your IE code is correct)
function getHeight() {
var doc = document.getElementById('div.right');
if (document.all) // ok I.E
{
H = doc.currentStyle.height;
}
else // ok FF
{
H = document.defaultView.getComputedStyle(doc, null).height;
}
document.getElementById('div.left').style.height = H;//✔
}
Just to help people I found a great code to change the height of two div autoamtically using a little of Jquery :
<script type='text/javascript'>
$(window).load(function(){
var lh = $('#div.right').height();
var rh = $('#div.left').height();
if (lh >= rh){
//alert('left : ' + lh);
$('#div.left').height(lh);
} else {
//alert('right : ' + rh);
$('#div.right').height(rh);
};
});
</script>
It's works for all navigators.

Detecting width: auto in jQuery

I'm retrieving the width of elements using jQuery and would prefer it if I could have an indication of whether there was an explicit width (and height) specified.
<div id="test"></div>
<script type="text/javascript">
$(function() { alert($('#test').css('width')); });
</script>
This will alert the implicit width of the div in terms of how many pixels it takes up on the client's screen. Is there any way that if the width is either missing or set as width: auto that it can be verified using jQuery?
That is, instead of the above example returning an integer, it would return either auto or undefined. Or, alternatively, is there an equivalent of a isAuto function?
This will get either string "auto" or "180px" on absolute values.
$('element').prop('style').width
for width or
$('element').prop('style').height
for height.
I don't believe it's possible for the moment. At least not in any other browser than IE. IE implements element.currentStyle which represents styles at they were written in the CSS file. On the other hand, the rest of the browsers implement window.getComputedStyle which returns the computed values of those styles. That's what you receive there, a numeric value instead of auto.
The only way around it would be to parse CSS declarations from document.styleSheets.
References:
http://msdn.microsoft.com/en-us/library/ms535231(VS.85).aspx
https://developer.mozilla.org/en/DOM:window.getComputedStyle
https://developer.mozilla.org/en/CSS/computed_value
$('#test')[0].style.width=="auto" should work: http://jsfiddle.net/KxTLE/ and http://jsfiddle.net/KxTLE/1/
Try
jQuery.fn.isAuto=function() {
if(this[0]) {
var ele=$(this[0]);
if(this[0].style.width=='auto' || ele.outerWidth()==ele.parent().width()) {
return true;
} else {
return false;
}
}
return undefined;
};
And example: http://jsfiddle.net/KxTLE/6/
As far as I know, there is no native jQuery function to detect auto widths or heights. So I wrote a plugin to do it.
$.fn.isAuto = function(dimension){
if (dimension == 'width'){
var originalWidth = this.innerWidth();
var marginLeft = parseInt(this.css('margin-left'));
var testMarginWidth = marginLeft+50;
this.css('margin-left', testMarginWidth);
var newWidth = this.innerWidth();
this.css('margin-left', marginLeft);
if(newWidth<originalWidth){
return true;
}
else{
return false;
}
}
else if(dimension == 'height'){
var originalHeight = this.height();
this.append('<div id="test"></div>');
var testHeight = originalHeight+500;
$('#test').css({height: testHeight});
var newHeight = this.height();
$('#test').remove();
if(newHeight>originalHeight){
return true;
}
else{
return false;
}
}
};
Originally, I had written it to do height, so I just expanded it to include width. You just call it like this:
$('#element').isAuto('width');
or
$('#element').isAuto('height');
Here is a fiddle demonstrating the plugin's functionality.
I am not quite sure if I am answering your question correctly, but if you use the width() function this will give you an integer representing the rendered width in pixels.
create function
pass css element id to function
write a case where statement to be performed on the width property of the element id
NOTE: to use on mulitple elements would be wise to use a loop with an array of element names

Categories

Resources