Clear out previous value when new value displays - javascript

I've been creating this simple program to calculate screen width and height when resizing page. It gives the width and height of the page on load as the default but each time I resize it a new value gets displayed along with the previous one. I want only to display the new value. How can I do that?
Here's the HTML
<body onload="getSize()" onresize="getSize()">
<div id="wh">
<!-- Place height and width size here! -->
</div>
Here's the JS
function getSize(){
let w = window.innerWidth;
let h = window.innerHeight;
let displayThis = "Width is " + w + " and height is " + h;
display.append(displayThis);
}

display.append(displayThis); means to add text after previous text, if you want to replace previous one,use this:
display.innerHtml = displayThis
this just replace element's inner html everytime, just keey the final one.

Related

jQuery each() function not working after if/else statement has been completed for both if and else outputs

I am using jQuery & javascript to switch the classes for images based on whether the viewport width is less than or greater than twice the width of the image.
I am using $(window).resize to detect when the widow is resized and then the each() function to iterate through all images of a certain class.
An if statement checks whether the width of the viewport is less than twice the width of the image and if so removes one class and adds another. The else statement does the reverse.
One page load it works fine for as many widow width changes as I do, until both the if and the else have been executed, then they stop working. Any suggestions would be greatly appreciated!
Thanks
Here's my code:
function updateViewportDimensions() {
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName("body")[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight || e.clientHeight || g.clientHeight;
return { width: x, height: y };
};
jQuery(window).resize(function() {
var viewport = updateViewportDimensions();
var viewport_width = viewport['width'];
console.log('Viewport width = ' + viewport_width);
jQuery(document).ready(function($) {
$('.alignright').each(function(i, obj){
// get the width of each image
var image_width = $(this).width();
// if the viewport width is less than twice the image width then switch the classes
if(viewport_width < (image_width * 2)) {
$(this).removeClass('alignright');
$(this).addClass('aligncenter');
console.log('Viewport is less than twice image width');
} else {
console.log('Viewport is more than twice image width');
$(this).addClass('alignright');
$(this).removeClass('aligncenter');
};
});
});
});
If I am reading this correctly, (this).removeClass('alignright'); is changing your dom. Because of this all the link to the class alignright is now new but your jquery is still looking for the instances that have been removed.
Update $('.alignright').each(function(i, obj){ to be one level higher than what is being altered.
if the code is
<div id="outer-wrapper">
<div class="alignright">
content
</div>
</div>
use $('#outer-wrapper .alignright').each(function(i, obj){

Jquery horizontal slide based on div width

I have jquery script where you can click a left and right button and it will scroll horizontally to show more content.
The content that needs to be scrolled are in a div with a width of 1296px, but i want to set my jquery code to automatically get the width of the div and when you press on one of the left or right scroll button it will scroll exactly 1296px.
I want to do it this way because I need to later on optimize the design for all screen size and this would be the easier way.
My code:
var $item2 = $('div.group'), //Cache your DOM selector
visible2 = 1, //Set the number of items that will be visible
index2 = 0, //Starting index
endIndex2 = ( $item.length ); //End index
$('#arrowR').click(function(){
index2++;
$item2.animate({'left':'-=1296px'});
});
$('#arrowL').click(function(){
if(index2 > 0){
index2--;
$item2.animate({'left':'+=18.5%'});
}
});
This Javascript should work:
var $item2 = $('div.group'), //Cache your DOM selector
visible2 = 1, //Set the number of items that will be visible
index2 = 0, //Starting index
endIndex2 = ( $item2.length ); //End index
var w = $("#group").width();
$('#arrowR').click(function(){
index2++;
$item2.animate({'left':'-=' + w + 'px'});
});
$('#arrowL').click(function(){
if(index2 > 0){
index2--;
$item2.animate({'left':'+=' + w + 'px'});
}
});
Check this fiddle. Basically we calculate the width initially to not do the same thing repeatedly and the reuse it whenever we need it.
Why not get the width of the visible container first, and then use that value later? Quick example:
var width = $('container').width();
And then during animations:
var left = $item2.css('left') + width;
$item.animate({'left',left});
As a note, innerWidth and outerWidth may be more beneficial than just width depending on how you've set everything up, so if values aren't quite right take a look at those documents.
I've created a fiddle that I think solves your problem:
http://jsfiddle.net/77bvnw3n/
What I did was to create another variable (called width) which on page load, dynamically gets the width of the container.
var width = $('.group-container').width(); //Container Width
This variable is also reset whenever the Next or Previous buttons are pressed (in case the window has been resized since the page loaded).
$('#arrowR').click(function(){
index2++;
//recheck container width
width = $('.group-container').width();
$item2.animate({'left':'-=' + width + 'px'});
});
Take a look and let me know if it helps.
Note: I replaced the 'Next' and 'Previous' images with coloured boxes in my Fiddle and I think you also had a typo in your code, should
endIndex2 = ( $item.length )
be changed to:
endIndex2 = ( $item2.length )

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!

How to make a function set css width with a JavaScript variable?

I have this code:
...<script>
function handleSize()
{
var setObjectSize=window.innerWidth - 600;
document.getElementById("spin").style.width=setObjectSize + "px";
document.getElementById("spin").style.height=setObjectSize + "px";
}
</script>
</head>
<body>
<section id="spin" onLoad="handleSize()">...
All I am trying to do is to create a function that will set the height and width of the element according to window size using a formula and make sure height and width are the same. I am very new to javascript (almost know nothing about it), so despite there being a ton of example of such questions, and me following them, I can't get this code to work. What am I doing wrong?
The problem that I'm seeing, is that the onload event for the section tag isn't firing. You should add your javascript as a self-executing anonymous function to the end of your body tag and this will work for you.
<body>
<section id="spin" style="border:5px solid black;"></section>
<script>
(function () {
var setWindowSize = window.innerWidth - 600;
document.getElementById("spin").style.width = setWindowSize + "px";
document.getElementById("spin").style.height = setWindowSize + "px";
})();
</script>
</body>
See Here for a demo: http://jsfiddle.net/T7DW6/
You should move onload to the body tag:
<body onLoad="handleSize()">
<section id="spin">...
I would suggest you to use jQuery, that is JavaScript library used world wide. So in order to develop it using jQuery you need to do next
function setElementSize(elId) {
var _w $(window); //to get instance of window
var _el $('#' + elId); //jquery to get instance of element
var _width = _w.width();
var _height = _w.height();
//set width=height
if(_height>_width)
{
_height = _width;
} else { _width = _height; }
_el.css({
width: _width,
height: _height
});
}
//this will execute script when document is loaded.
$(document).ready(function(){
setElementSize('spin');
});
Function above will set width and height of element to match window size. If height > width then it will use width as width & height otherwise it will use height.
I assume that you want to change this automatically if window is resized then do this
$(window).resize(function(){
setElementSize('spin');
});
The onload event occurs when an object has been loaded.
onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
onload is only Supported by the Following HTML Tags:
body, frame, frameset, iframe, img, input type="image", link, script, style
from here: event_onload
then a is may be not the best here (height and weight does not change anything, you should use a div.
In order to know, the one to use, please read this:
what-is-the-difference-between-section-and-div
I try your exam and it works fine. The only thing that i changed was the way that you call the function
function handleSize(){
var setWindowSize=window.innerWidth - 600;
document.getElementById("spin").style.width=setWindowSize + "px";
document.getElementById("spin").style.height=setWindowSize + "px";
}
window.onload = function () {
handleSize();
}
I think that onLoad="handleSize()" have to be onload="handleSize()" but don't use that way because it is not a good practise!
this works for me
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button and watch it grow.</p>
<button id = "myButton" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var w = window.innerWidth;
var h = window.innerHeight;
var x = document.getElementById("myButton");
x.style.width = w + "px";
x.style.height = h + "px";
}
</script>
</body>
</html>

How to set percentage in Javascript for my progress bar?

I do not know anything in Javascript (I have copied a code for a progress bar but it does not display the percentage). I just need to display the text value of the actual % inside my progress bar (a text such as : 1%, 2%, 3%...).
The existing code I have is the following (I do not care about the style, so I removed it to read the code easier) :
<div id="loading">
<div id="progressbar">
<div id="progress"/>
<script>
var loading = document.getElementById('loading');
var progress = document.getElementById('progress');
var progressbar = document.getElementById('progressbar');
function updateProgress()
{
if (loading.style.display !== 'none')
{
var width = parseInt(progress.offsetWidth + ((progressbar.offsetWidth - progress.offsetWidth) * .15));
if (width > (progressbar.offsetWidth * .95))
width = parseInt(progressbar.offsetWidth) * .5;
progress.style.width = width + 'px';
window.setTimeout("updateProgress()", 1000);
}
}
document.body.style.margin = 0;
document.body.style.padding = 0;
loading.style.display = 'block';
updateProgress();
</script>
</div>
</div>
Can you help me to add the missing code to display a text having the percentage already loaded please ?
https://developer.mozilla.org/en/DOM/element.innerHTML -- this is the element property to set the content of an element.
Assuming your progress percentage is defined as var percent, you'll just need to set the content as such:
progress.innerHTML = percent.toFixed(1) + '%';
Instead of this, you may try Query Loader.
This preloader has it all. Loading bar, custom animations and getting all images included in the web page.
You can see a demo here

Categories