jquery get inner width returns different values - javascript

I am trying to get inner width of a div using jquery. The code I used to do so is as below
$(document).ready(function(){
console.log("width : "+$("div").innerWidth());
}
But the code returns different values every time I refresh the page. Sometimes it returns 971 and sometimes it returns 1336,The actual width I have set to that particular division in CSS style sheet is 800px. Can anybody please tell me What's wrong in my code? and how can I get the right innerwidth?
Note: I need innerwidth to make a division responsive. I am displaying a chart in that division and I want my chart to be responsive.

add ); to your script end.
$(document).ready(function(){
console.log("width : "+$(".div").innerWidth());
});
.div{width:800px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">dghgdh</div>

$(document).ready(function() {
var select = $('div');
console.log('innerWidth: ' + select.innerWidth(), 'innerHeight: ' + select.innerHeight());
console.log('clientWidth: ' + select[0].clientWidth, 'clientHeight: ' + select[0].clientHeight);
console.log('offsetWidth: ' + select[0].offsetWidth, 'offsetHeight: ' + select[0].offsetHeight);
console.log('width: ' + select.width(), 'height: ' + select.width());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Hello World!</div>

i think your problem is scroll bar.You can try it
window.innerWidth: with scrollbar
$(window).width(): without scrollbar

Related

How to get bootstrap modal size

I have a bootstrap modal whose size is set by:
<div class="modal-dialog modal-lg">
I want to be able to determine the modal's size (width actually) before I make a post request to a PHP program to display some dynamic content before displaying the modal. Does anyone know how to get this information?
I have also been trying to find either the width or height of the entire modal as well as the modal classes and found this solution. Though I must add that with this approach the width and height of the modal are only found after it has loaded.
I think that it is not possible to get the correct width and height of the modal before it is being displayed since it is hidden by default before the user clicks to open it. style="display: none; as inline style under the modal class in Bootstrap 3.3.2.
However if you like to get the correct width and height of modal once it is displayed you can use this approach.
// once the modal has loaded all calculations can start
// since the modal is hidden before it is loaded there are
// no dimesions that can be calculated unfortunately
$('#myModal').on('shown.bs.modal', function () {
// get the viewport height
var viewportHeight = $(window).height();
console.log ('viewportHeight = ' + viewportHeight);
// get the viewport width
var viewportWidth = $(window).width();
console.log ('viewportWidth = ' + viewportWidth);
// get the .modal-dialog height and width
// here the .outerHeight() method has to be used instead of the .height() method
// see https://api.jquery.com/outerwidth/ and
// https://api.jquery.com/outerheight/ for reference
// also the .find() method HAS to be used, otherwise jQuery won't find
// the correct element, this is why you got strange values beforehand
var modalDialogHeight = $(this).find('.modal-dialog').outerHeight(true);
console.log ('modalDialogHeight = ' + modalDialogHeight);
var modalDialogWidth = $(this).find('.modal-dialog').outerWidth(true);
console.log ('modalDialogWidth = ' + modalDialogWidth);
// I have included a simple function to log the width and height
// of the modal when the browser window is being resized
var modalContentWidthHeight = function () {
var modalContentWidth = $('#myModal').find('.modal-content').outerWidth(true);
console.log ('modalContentWidth = ' + modalContentWidth);
var modalContentHeight = $('#myModal').find('.modal-content').outerHeight(true);
console.log ('modalContentHeight = ' + modalContentHeight);
};
$(window).resize(modalContentWidthHeight);
});
I hope the above code somehow helps you figure out the modal dimensions and that you can take it from there..
Another thing that was really bugging me that you might encounter when using the Bootstrap 3.3.2 modal. If you like to get rid of this bug Open modal is shifting body content to the left #9855 concerning the modal position and given this bug it still not fixed Modify scrollbar check, stop static nav shift #13103 you can use this approach that works regardless of if you have a vertical scrollbar shown or not.
Reference: Bootstrap 3.3.2 Center modal on all viewport sizes with or without vertical scrollbar
$('#myModal').on('shown.bs.modal', function () {
// meassure the padding-right given by BS and apply it as padding-left to the modal
// like this equal padding on either side of the modal is given regardless of media query
var modalPaddingRight = $('#myModal').css('padding-right');
console.log ('modalPaddingRight = ' + modalPaddingRight);
// apply the padding value from the right to the left
$('#myModal').css('padding-left', modalPaddingRight);
console.log (
'modalPaddingLeft = ' + $('#myModal').css('padding-left') +
' modalPaddingRight = ' + $('#myModal').css('padding-right')
);
// apply equal padding on window resize
var modalPaddingLeft = function () {
var modalPaddingRight = $('#myModal').css('padding-right');
console.log ('modalPaddingRight = ' + modalPaddingRight);
$('#myModal').css('padding-left', modalPaddingRight);
console.log (
'modalPaddingLeft = ' + $('#myModal').css('padding-left') +
'modalPaddingRight = ' + $('#myModal').css('padding-right')
);
};
$(window).resize(modalPaddingLeft);
});
I hope some of this answer can help you. Since I am new to jQuery there might be better or more elegant ways to actually code this, though I would not know how at this stage. Nevertheless I think the information given here might be of help to you.
If you want the actual dimensions of an element using Javascript, JQuery has the built in .width() and .height() functions. I modified your <div> to add a data- attribute that has the bootstrap class incase you want to access that and an ID for easier access:
<div id="my_modal" class="modal-dialog modal-lg" data-size="modal-lg">
Then access it via Javascript:
var width = $("#my_modal").width();
var height = $("#my_modal").height();
var size = $("#my_modal").attr("data-size");
console.log("Width Is: " + width + " and Height Is:" + height + "and Size Is:" + size);
Hope that helps!

getting top and left position of colorbox at runtime

Been trying to get the top and left coordinates colorbox loaded content, but I keep getting either 0 or auto.
I'm executing the following in onComplete callback:
var cboxLeft = $('#cboxContent').css('left');//.position().left;
var cboxTop = $('#cboxContent').css('top');//.position().top;
console.log( 'cboxLeft: ' + cboxLeft + ' cboxTop: ' + cboxTop );
Right now console gives me: cboxLeft: 0px cboxTop: 0px
What I'm really after is appending custom close button to BODY. I need it accessible outside the cboxLoaded* area and visible. Hence trying to get position of content once colorbox is done with it.
.css() will not return these properties. You'll have to use .offset() instead.
So the code should look like:
var cboxLeft = $('#cboxContent').offset().left;
var cboxTop = $('#cboxContent').offset().top;
console.log( 'cboxLeft: ' + cboxLeft + ' cboxTop: ' + cboxTop );
Note: This gives the position relative to the document. If you want where it is on the current viewport (current view of the browser window), you might want to subtract window.scrollX and window.scrollY respectively.

Javascript : Why Can’t I Read the ‘object.style.left’ & ‘object.style.top’ values?

Why Can’t I Read the object.style.left & object.style.top values ?
I’m trying to dynamically move a button.
I can use javascript to reset the style.left & style.top values by doing this :
document.getElementById(theButton_ID).style.left = "128px";
document.getElementById(theButton_ID).style.top = "64px";
But my problem is that I need to dynamically reset the ‘style.left’ & ‘style.top’ values, using a scaling factor that needs to be dynamically determined when the web page loads.
To my novice way of thinking this means that I need to :
• Get the style.left & style.top values
• Multiply them by the scaling factor
• Assign those modified values to style.left & style.top values.
The problem is that I can’t get the style.left & style.top values in the 1st place so I can’t modify them, much less write them back.
So obviously, I’m both doing something wrong & I'm not understanding something I should understand.
So what am I doing wrong ?
What is it that I’m missing ?
And Most importantly, how do I get the value of style.left & style.top so that I can use them to dynamically modify the position of the button ?
Thanks everyone for all your help & suggestions.
Here’s the actual HTML / CSS/ Javascript code …
<html>
<head>
<title>Button Dynamic Move Test</title>
<style type="text/css">
#MoveButton
{
position : absolute;
left : 8px;
top : 16px;
}
</style>
<script>
// var X_Index_Move_Factor = 1.25;
// var Y_Index_Move_Factor = 1.50;
function Move_A_Button (theButton_ID)
{
alert ( "We're in 'Move_A_Button'"
+ "\n"
+ " The Button Id = "
+ theButton_ID
);
var the_Old_Button_X_Offset = document.getElementById(theButtonId).style.left;
var the_Old_Button_Y_Offset = document.getElementById(theButtonId).style.top;
alert ( "the_Old_Button_X_Offset = "
+ "\n"
+ the_Old_Button_X_Offset
+ "the_Old_Button_Y_Offset = "
+ "\n"
+ the_Old_Button_Y_Offset
);
}
</script>
</head>
<body>
<button type = "button"
id = "MoveButton"
onclick = "Move_A_Button ('MoveButton')">
About Us
</button>
</body>
</html>
Actually, if you don't need to support IE6 or IE7 (or FireFox from ~17 versions ago), then the best way to go about getting the internal data is something like this:
// inside of your function:
var el = document.getElementById(button_id),
dimensions = el.getBoundingClientRect();
console.log("old x: " + dimensions.left, "old y: " + dimensions.top);
console.log("new x: " + dimensions.left * scale_X, "new y: " + dimensions.top * scale_Y);
Just remember that when you set them, afterward, you have to add the measurement, as well:
el.style.top = (dimensions.top * scale_Y) + "px";
el.style.left = (dimensions.left * scale_X) + "px";
And that using the getBoundingClient function will give you measurements as numbers, but .style.top / .style.left will give you measurements as strings ("112px") which you then have to pull the numbers out of, and then modify, and then when you add them back, you add the measurement type back on... ...hooray
theButton_ID is the name of an argument
function Move_A_Button (theButton_ID)
{
When you try to get the style you write
document.getElementById(theButtonId).style.left;
You forgot a underscore
Even with the typos corrected, the element doesn't initially have top or left styles, since none are set on the element itself.
element.offsetLeft and element.offsetTop are your best bets as starting points.

Setting innerhtml after displaying an element

Is it OK to set the html of the element after the element is displayed. Will the user find any visible difference in this case. For Eg.
$("#abc").show();
$("#abc").append("<div>Test div</div>");
Also I would like to know if this would cause unwanted browser repaints.
Thanks,
Gautham
May be this could help: fiddle
$('button').click(function () {
console.log('Height is ' + $("#abc").height() + ' before show.');
$("#abc").show();
console.log('Height is ' + $("#abc").height() + ' after show.');
$("#abc").append("<div>Test div</div>");
console.log('Height is ' + $("#abc").height() + ' after filling.');
});
outputs:
Height is 0 before show.
Height is 0 after show.
Height is 20 after filling.
browser-reflows-repaint for info

Trouble creating multiple generated sticky headers using jQuery and CSS

I am trying to integrate a sticky headers technique like the one shown here... Persistent Headers.
I have tried to integrate it into my code and for the most part have been successful, however it isn't behaving correctly and I REALLY can't figure it out.
I'll try to explain in a nutshell what the page it is being used on does. I have a database with a table of students and another table of assessments. This page loops through a JSON object (recieved from the database via a PHP script) and then for each student in that first object fetches another JSON with their assessments. This all works fine. It does however create a fairly long page. Visually it looks like this...
Code rendered in Chrome
The code I have written based on that tutorial I posted above is supposed to clone headers specified by a class and then hide or show them based on some logic involving scrollTop the position of the element and the length of the element. This having the effect of the header sticking to the top of the page while the container it belongs to is still visible.
The problem is something is going wrong and although all the headers are shown in sequence they are way too early, they seem to hang about for different lengths of time, and these lengths do seem to correlate to how long the container it belongs to is.
So my code...
Firstly the function used to update the headers...
containerArray = new Array;
positionArray = new Array;
floatingHeaderArray = new Array;
function updateTableHeaders() {
$(".studentContainer").each(function(i) {
containerArray[i] = $(this);
var position = containerArray[i].position();
positionArray[i] = position.top;
var scrollTop = $("#main").scrollTop();
floatingHeaderArray[i] = $(".floatingHeader", this);
if ((scrollTop > positionArray[i]) && (scrollTop < positionArray[i] + containerArray[i].outerHeight(true))) {
floatingHeaderArray[i].css({
"visibility": "visible"
});
} else {
floatingHeaderArray[i].css({
"visibility": "hidden"
});
};
});
}
Now the code that generates the containers, headers and tabs.
$("#mainContent").fadeIn(0);
loadMessage = "Loading data for " + event.target.id;
$.getJSON('php/oneFullClass.php?techClass=' + event.target.id, function(data) {
$('#mainTitle').fadeOut(0);
$('#action').html('You are ' + actionIntent + 'ing ' + event.target.id);
$('#action').fadeIn(300);
$('#mainTitle').fadeIn(300);
$('#mainContent').append('<div id="scrollTopDisplay"></div>')
dynamicPositioning();
$.each(data, function(key, val) {
var thisPosition = positionArray[0]
$('#mainContent').append(
'<div class="studentContainer studentView" id="' + val.idStudent + '">' +
'<div class="studentName">' + val.name + ' ' + val.surname + ' - (' + val.form.substr(0, 1) + '/' + val.form.substr(1, 2) + ')</div>' +
'<div class="floatingHeader">' + val.name + ' ' + val.surname + ' - (' + val.form.substr(0, 1) + '/' + val.form.substr(1, 2) + ')</div>' +
'<div class="studentTarget"> Target: <strong>' + val.target + '</strong></div>' +
'</div>');
$(".studentContainer").hide().each(function(i) {
//$(this).slideDown(0);
$(this).delay(i * 50).slideDown(300).fadeIn(500);
})
//Get previous assessments for this student and build tabs
buildTabs('php/allPreviousAssess.php?sid=' + val.idStudent, val.idStudent);
});
});
$('#mainContent').append('<div id="expandAll" onClick="expandAll()">Expand</div>');
$('#mainContent').append('<div id="collapseAll" onClick="collapseAll()">Collapse</div>');
dynamicPositioning();
$('#expandAll').delay(300).fadeIn(300);
$('#collapseAll').delay(300).fadeIn(300);
$("#main").scroll(updateTableHeaders);
I think that's all the info you'll need but I'll post any other code that may be referenced in this code if you think it'll help figure it out.
I have a suspicion that the problem is something to do with the animated slide in effect I am using on the 'assessment cards' messing with the position values, or possible position()'s inability to get positions of hidden elements. However, as I call updateTableHeaders() with every scroll event, this shouldn't be an issue as all animation is over by the time you are given access to the layout (there is a modal shade effect that only dissapears once all AJAX requests are complete.
I hope someone can help, this one is making me unhappy! :(
Balloon, a library I wrote for easily making your headers stick, is pretty hassle-free. You simply make a Balloon object instance, specifying if you want your sticky headers to be stacked or replaced, and then inflate the headers by passing in the strings of their ids. Give it a try and let me know if it helped you:
https://github.com/vhiremath4/Balloon
If you find any issues with it, file a bug report on the repository, but I feel like it should do its job in your case.

Categories