i cant get the correct height() and get width() - javascript

I have a function that is called when a button is clicked.
The function first changes the size of the control and then i have 2 lines of code that fetch the height and width of a control and display them in the paragraph as text.
When the user first clicks on the button they will get the wrong values of 340*150 and when they click the button again they get the correct values 600*400
the 340*150 is the old/original size before the control expands.
However on the first click even though the wrong values are displayed i still get the correct control size of 600*400 displaying.
function a () {
//change control to 600*400
//now get the height and width and display in 'p' and 'g'.
document.getElementById('p').innerHTML = jQuery("#hi").width();
document.getElementById('g').innerHTML = jQuery("#hi").height();
}
<button id="btn" onClick="a()"> Maximize 600x400 </button
also using settimeout function resolves the issue. but i want to fix it properly.

Could you do something like this?
function a () {
var w = 600;
var h = 400;
// change control to 600*400 using the w and h variables
// code to do that here ...
// now get the height and width and display in 'p' and 'g'.
document.getElementById('p').innerHTML = w;
document.getElementById('g').innerHTML = h;
}
<button id="btn" onClick="a()"> Maximize 600x400 </button
If the size of your element is properly being changed then the numbers should be the same either way. No need to get the numbers from the element.

If you create an event on page load, say btnResize, then you can emit it after the resize, it will solve your problem. jQuery uses trigger() to emit an event.
function a(){
$('#hi').width(600);
$('#hi').height(400);
$('#hi').trigger('btnResize');
}
$('#hi').on('btnResize', function(){
$('#p').html($('#hi').width());
$('#g').html($('#hi').height());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn" onClick="a()"> Maximize 600x400 </button>
<div id="p"></div>
<div id="g"></div>
<br>
<button id="hi" style="width:340px; height:150px;" > resize me </button>
I believe your issue was as simple as the asynchronous nature of JavaScript. You were getting the width and height before the function a() was called.

Related

Javascript event which occurs when resizing a DOM element?

Im working on a project in which the height value of a resizable div always needs to be divisible by 24 (This is so it always matches the default lineheight). I have created a function for resizing the div and i now need to run the function whenever the div is resized. Events that fire when the entire window is resized exist but im not able to find any events which fire when a specific DOM element is resized.
The following is my code:
HTML
<body>
<div id="resizable-div" onresize="changeHeight()"></div>
<body>
Javascript
let resizeDiv = document.getElementById('resizable-div');
function changeHeight(){
if (resizeDiv.style.height % 24 != 0) {
resizeDiv.style.height = `${Math.round(resizeDiv.offsetHeight / 24) * 24}px`
}
}
I was expecting the above code to change the height of resizable-div whenever it was resized. It doesn't, however when writing my code like this:
<body onresize="changeHeight()">
<div id="resizable-div"></div>
<body>
It produces the outcome im looking for, but only whenever the size of the entire viewport is changed. How can i call my function whenever the height of my resizable-div changes?
After deciding to use my brain the solution was painfully simple. Since the div is resized by the user dragging it, i can simply add an event listener to the resizable-div which listens to the mouseup event. Here is the code:
HTML
<body>
<div id="resizable-div"></div>
<body>
Javascript
let resizeDiv = document.getElementById('resizable-div');
function changeHeight(){
if (resizeDiv.offsetHeight % 24 != 0) {
resizeDiv.style.height = `${Math.round(resizeDiv.offsetHeight / 24) * 24}px`
}
}
resizeDiv.addEventListener('mouseup', (event) => {
changeHeight();
})
This will make the div snap to the closest height that is divisible by 24 whenever the user stops dragging it.

change textbox width based on it's value

I am trying to change my textbox's width according to textbox's value but it does not seems like working.
Here is my aspx:
<asp:TextBox ID="TxtbSizeOzel" runat="server" CssClass="text-center"></asp:TextBox>$
I create an onKeyUp event for resizing method in codebehind:
TxtbSizeOzel.Attributes.Add("onKeyUp", "Expand(this)");
And lastly my javascript method:
function Expand(obj)
{
if (!obj.savesize) obj.savesize = obj.size;
obj.size = Math.max(obj.savesize, obj.value.length);
}
I don't get any error but it just doesn't working.
UPDATED WITH CODE EXPLANATION:
here you go, the input will always be as long as its characters, whether you type, remove or give it a value before running the script: Demo here
//this is a plugin snippet (or function) to check if the element has
//horizontal scrollbar
$.fn.hasHorizontalScrollBar = function() {
if (this[0].clientWidth < this[0].scrollWidth) {
return true
} else {
return false
}
}
//the end of plugin
var originalWidth=$('.txt').width(); //we store the original width
//(the width of the input at the page load) in a variable to use it as a
//measurement in order to not let the input get smaller than this size
//this function checks the width of `.txt` (the input) to see if it has
//horizontal scrollbar or not, if it does then expands the width of the input to
//the scroll size, else it checks to see if the width is added to the
//original width, if so, removes one character (depending on the font size it'll
//change - here it is 7 px)
function changeWidth(){
if($('.txt').hasHorizontalScrollBar()){
$('.txt').width(document.getElementsByClassName('txt')[0].scrollWidth);
}
else if(originalWidth<$('.txt').width()){
$('.txt').width($('.txt').width()-7);
}
};
//end of the function
changeWidth(); //run the function at page load, to give the input a size as wide as its
// character's length
$('.txt').keydown(changeWidth); //assign the function to the keydown event of the input
//so whenever a character is added or removed the function will run again
Try using .width() property of JQuery. It supports the get and set operations for width manipulation of controls or elements in your HTML.
And you can try this if you want to go with JavaScript :
document.getElementById("yourControlId").style.width = "300px";
Hope this helps.

Angular ng-show callback

I am trying to get the height of an element which will appear when mouse over of a button.
Example code:
<div ng-mouseenter="mouseoverPopUp()" ng-mouseleave="showpop=false">menu</div>
<div class="popover" ng-show="showpop">{{content}}</div>
$scope.mouseoverPopUp = function($event){
$scope.showpop = true;
var height = angular.element(".popover").innerHeight();
};
The problem is sometimes the height of the element is being get before it is appeared. Is there anyway I can run the code only have the ng-show has show the element? I need to get the height ASAP after it appear to adjust the position of the element.
Have you tried with your code inside a $timeout call in order to delay the execution of your JS after angular finished working ?
$scope.mouseover = function($event){
$timeout(function() {
var height = angular.element(".popover").innerHeight();
});
};
How are you showing your popover? with a css transition ? If so you'll need to delay accordingly your JS code retrieving the height. Or you can use angular-animate to bind events with more logic
ps: to help more, a jsfiddle would be great

Button onclick doesn't respond

I am fairly new to JavaScript and I am trying to make my own image gallery as my first simple project. I expected it to go smoothly, but it seems like I am doing some trivial mistake, and I have no idea where.
So, my initial plan was: I would set up an image element with empty src property, create an array of image names, add a function that will increase the array pointer by 1 any time it is triggered, and then just add the corresponding value in the array to the src.
It doesn't work, though. Could you please try to see any errors in the code? I really have no idea what to do, just can't find a mistake.
<html>
<body>
<img src="" id="imageCanvas">
<div id="counterDisplay"></div>
<script type="text/javascript">
var images = ["increased.jpg","knight.jpg","knight-g.jpg","golden.jpg","land.jpg"];
var counterDisplay = document.getElementById("counterDisplay");
var imageCanvas = document.getElementById("imageCanvas");
var imageCount = 0;
// function intended to increase the array position indicator by 1, but it always only increases it in relation to the original imageCount value (0), how to make it save the already increased value?
function changeCount() {
imageCount = imageCount+1;
}
counterDisplay.innerHTML = imageCount;
imageCanvas.setAttribute("src",images[imageCount]);
</script>
// The main problem: it just refuses to respond!
<button onclick="changeCount()">NEXT</button>
</body>
</html>
I didn't debug through this, but my guess is that onclick is being called, but you are not updating the count in that changeCount code.
Try putting almost all the code in changeCount.
function changeCount() {
imageCount = imageCount+1;
counterDisplay.innerHTML = imageCount;
imageCanvas.setAttribute("src",images[imageCount]);
}
This function runs when the the button is clicked.
function changeCount() {
imageCount = imageCount+1;
}
This code is run when the script first loads.
counterDisplay.innerHTML = imageCount;
imageCanvas.setAttribute("src",images[imageCount]);
You want it to run when the button is clicked. Move it inside the function.

After resizing the window, elements within do no fit anymore

I have a modal dialog (window.showModalDialog) with html in it. when I resize the dialog, the HTML within it does not repect the new boundaries and I get scroll bars or elements that don't expand 100% to the new width.
To fix this I have to drag it around for a bit and it then jolts it self back into the correct sizes.
To fix it programtically. I do the following window.document.getElementById('removeMainBody').innerHTML =window.document.getElementById('removeMainBody').innerHTML;
But this causes some dynamic objects in the html to stop functionin.
How can i solve this problem and make the elemnts within the dialog resize after I resize the dialog?
Here is my code
else if(<c:out value="${staffCount}" /> > 1){
document.getElementById('removeDiv').style.display = '';
window.dialogWidth='770px';
window.dialogHeight='320px';
window.document.getElementById('removeMainBody').innerHTML =window.document.getElementById('removeMainBody').innerHTML;
}
If you set a style or a Class from the Body-Tag, this should force an HTML Reflow, and the Site would be displayed correct again, without setting the innerHTML Property.
example:
...
window.document.body.className = "relfow";
// if the body class Attribute was set, than set it now back
window.document.body.className = "oldBodyStyleClassName" ; / Or just to ""
...
if the browser optimizes, the refresh calls, so that now reflow occures you could
setTimeout(function(){
...
window.document.body.className = "relfow";
// if the body class Attribute was set, than set it now back
window.document.body.className = "oldBodyStyleClassName" ; / Or just to ""
...
})
i hope this helps. (here you can find some info to Reflow Link)

Categories