Positioning an image in middle of the screen - javascript

Hi can someone please tell me how to position an image in the centre of the screen using javascript?
Would I get the screen height and divide by 2? How would I get the screen height?
Thanks!

Really, CSS is the best way to do this (as per Sebastián's answer), and if you have to use JS then go for jQuery. However you asked for a javascript solution so you'll find one below.
Really the only two reaons I can see js being necessary are:
If the image is to be centered as a result of user interaction or
If the image has to be centered once, and then should remain static (instead of remaining centered, as would happen with a CSS solution).
Anyways... enjoy:
Usage:
imgToMiddle('imageid');
Note that 'imageid' is the id of the image you want to place in the screen's center. The function modifies the image's css properties to place it in the middle of the screen.
Code:
//viewport width/height code from here: http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
function imgToMiddle(imgid){
function viewportWidth(){
var viewportwidth;
if (typeof window.innerWidth != 'undefined'){
viewportwidth = window.innerWidth;
}
else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0){
viewportwidth = document.documentElement.clientWidth;
}
else{
viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
}
return viewportwidth;
}
function viewportHeight(){
var viewportheight;
if (typeof window.innerWidth != 'undefined'){
viewportheight = window.innerHeight;
}
else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0){
viewportheight = document.documentElement.clientHeight;
}
else{
viewportheight = document.getElementsByTagName('body')[0].clientHeight;
}
return viewportheight;
}
var img=document.getElementById(imgid);
img.style.position="absolute";
img.style.left=viewportWidth()/2-img.width/2;
img.style.top=viewportHeight()/2-img.height/2;
}

Centering with CSS:
http://www.bluerobot.com/web/css/center1.html
http://www.spanish-translator-services.com/espanol/t/007/center.html
http://simplebits.com/notebook/2004/09/08/centering/
Centering with javascript (jQuery):
Using jQuery to center a DIV on the screen

This is a modification of Cam's answer (which I got to work with some slight modification). This answer features a little more jQuery, and most importantly, the position:fixed, so that the resulting div will always be squarely in the middle of your viewport, no matter how far down or up you have to scroll.
function imgToMiddle(imgid){
function viewportWidth(){
var viewportwidth;
if (typeof window.innerWidth != 'undefined'){
viewportwidth = window.innerWidth;
}
else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0){
viewportwidth = document.documentElement.clientWidth;
}
else{
viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
}
return viewportwidth;
}
function viewportHeight(){
var viewportheight;
if (typeof window.innerWidth != 'undefined'){
viewportheight = window.innerHeight;
}
else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0){
viewportheight = document.documentElement.clientHeight;
}
else{
viewportheight = document.getElementsByTagName('body')[0].clientHeight;
}
return viewportheight;
}
var img=document.getElementById(imgid);
$(img).css("position","fixed");//note: position:"fixed" will keep the div exactly in the middle of your browser viewport. This can be useful as a modal dialog box.
$(img).css("left",parseInt(viewportWidth() / 2) - 100 );//note: "100" is half the width of the target div.
$(img).css("top",parseInt(viewportHeight() / 2) - 100 );//note: "100" is half the height of the target div.
}

Please refer to my following answer

Related

Resize window Automatically without reloading the page

My code works quite fine; if menu-1 is on width > 991 and I display it, it works; but if I resize it to check it media view, it is still set to display: block instead of being set to display: none that I have to use the toggle btn to display. I want my dropdown to be set to display: none if the window size changes. How can I go about that? Please kindly help me with this.
let viewpoint = window.innerWidth || document.documentElement.clientWidth;
window.addEventListener('resize', ()=>{
viewpoint = window.innerWidth || document.documentElement.clientWidth;
},true);
allPage.addEventListener('click', (event) =>{
if(viewpoint <=991){
backdbtn()
if(event.target == productBtn && viewpoint <= 991 ){
secondbtn()
if( menu1.classList.contains('product-d-none')){
menu1.classList.remove('product-d-none');
backBtn.classList.remove('v-none');
}
} if(event.target == backBtn || event.target == allPage){menu1.classList.add('product-d-none');
backBtn.classList.add('v-none')}
}
if(viewpoint >991){
secondbtn()
if(viewpoint !== 991){
backBtn.classList.add('v-none')}
if(event.target == productBtn && viewpoint > 991 ){
secondbtn()
if( menu1.classList.contains('product-d-none')){
menu1.classList.remove('product-d-none');
} else{menu1.classList.add('product-d-none');}
alert('window is less than 991')
}
else{menu1.classList.add('product-d-none');}
}
});
if(viewpoint > 991){
secondbtn()
menu1.classList.add('product-d-none');
productBtn.addEventListener('click', ()=>{
if( menu1.classList.contains('product-d-none')){
menu1.classList.remove('product-d-none');
secondbtn()
} else{menu1.classList.add('product-d-none');}
});
}

Append <div> into body just once

I'm trying to append a div when the mobile is in landscape mode. But I only want the div to be append once and one time only.
function doStuff() {
landscape = window.orientation ? window.orientation == 'landscape' : true;
if (landscape && window.innerWidth < 736 && window.innerWidth > 320) {
if (window.innerHeight > window.innerWidth) {
console.log("portrait");
} else {
$("body").append("<div>Test</div>");
}
}
}
window.onload = window.onresize = doStuff;
if (window.onorientationchange) {
window.onorientationchange = doStuff;
}
There's no need for JS code here - you can use CSS alone to achieve this. Media queries have the orientation restriction which you can use to display the required content:
.landscape-only { display: none; }
#media all and (orientation:landscape) {
.landscape-only { display: block; }
}
Working example
To see the content change you will just need to resize the width of the Output frame in the above Fiddle.
You can check if this div is already appended.
var appended = false;
function doStuff() {
if(appended) return;
landscape = window.orientation? window.orientation=='landscape' : true;
if(landscape && window.innerWidth < 736 && window.innerWidth > 320){
if(window.innerHeight > window.innerWidth){
console.log("portrait");
} else{
$("body").append("<div>Test</div>");
appended = true;
}
}
}
You could use one(), which fires only once
For Appending you need to use this
var $div = $('<div />').appendTo('body');
$div.attr('id', 'holdy');
Set flag = true if div is already appended.
function doStuff(){
landscape = window.orientation? window.orientation=='landscape' : true;
var flag = false;
if(landscape && window.innerWidth < 736 && window.innerWidth > 320){
if(window.innerHeight > window.innerWidth){
console.log("portrait");
}else{
if (flag == false){
$( "body" ).append( "<div>Test</div>" );
flag = true;
}else{
console.log("Div is already appended");
}
}
}
}
window.onload=window.onresize=doStuff;
if(window.onorientationchange){
window.onorientationchange=doStuff;
}
I think you can use the .one(). there is example of how use it on internet.
http://api.jquery.com/one/

How do I make the script work with percentage?

I have this pop up window being centered by javascript using px. I need the box to be responsive so how can I adjust the script to calculate for percentages and not px. Is it possible? This current code allows me to produce an automatic pop up but it also has script that centers the pop using px. This is not responsive.
function toggle(div_id) {
var el = document.getElementById(div_id);
if ( el.style.display == 'none' ) { el.style.display = 'block';}
else {el.style.display = 'none';}
}
function blanket_size(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportheight = window.innerHeight;
} else {
viewportheight = document.documentElement.clientHeight;
}
if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
blanket_height = viewportheight;
} else {
if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
blanket_height = document.body.parentNode.clientHeight;
} else {
blanket_height = document.body.parentNode.scrollHeight;
}
}
var blanket = document.getElementById('blanket');
blanket.style.height = blanket_height + 'px';
var popUpDiv = document.getElementById(popUpDivVar);
popUpDiv_height=blanket_height/2-187.5;//200 is half popup's height
popUpDiv.style.top = popUpDiv_height + 'px';
}
function window_pos(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportwidth = window.innerHeight;
} else {
viewportwidth = document.documentElement.clientHeight;
}
if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
window_width = viewportwidth;
} else {
if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
window_width = document.body.parentNode.clientWidth;
} else {
window_width = document.body.parentNode.scrollWidth;
}
}
var popUpDiv = document.getElementById(popUpDivVar);
window_width=window_width/2-250;//200 is half popup's width
popUpDiv.style.left = window_width + 'px';
}
function popup(windowname) {
blanket_size(windowname);
window_pos(windowname);
toggle('blanket');
toggle(windowname);
}
This seems like an awful lot of javascript to display a popup dialog. You can accomplish this functionality with CSS/HTML alone, although many solutions will use HTML/CSS for the layout, and some javascript to show/hide the dialog.
I dont like to use javascript at all for the actual layout of the webpage, such as positioning elements. CSS was designed specifically for positioning and styling web elements, and it is generally more efficient than JS.
You may want to check out some of the many guides available online for HTML/CSS Modal Dialogs. These are done with minimal javascript.
Check out this one for starters
http://www.webdesignerdepot.com/2012/10/creating-a-modal-window-with-html5-and-css3/
Good luck
You really don't need JavaScript to center something - for that, we have CSS! To center something horizontally, simply use the following CSS on the element
margin: auto;
To center something vertically, you can use something like
top: 50%;
transform: translateY(-50%);
position:relative;

Javascript : Ajax and Show/Hide Div

I use Ajax to request some information for my web page, and pops up a "Please Wait" window while the Ajax is running.
This is working fine in Mozilla and Chrome, but the "Please Wait" window does not show up in IE.
Here is my code :
function openWaitMessage()
{
var wid = 300;
var hgt = 200;
var left = 0;
var top = 0;
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
var scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset;
scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
//DOM compliant
scrOfY = document.body.scrollTop;
scrOfX = document.body.scrollLeft;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
//IE6 standards compliant mode
scrOfY = document.documentElement.scrollTop;
scrOfX = document.documentElement.scrollLeft;
}
left = scrOfX + (myWidth - wid)/2;
top = scrOfY + (myHeight - hgt)/2;
var div = document.getElementById("pleaseWait");
div.style.display = '';
div.style.visibility = 'visible';
div.style.left = left;
div.style.top = top;
} // openWaitMessage()
function getInformation {
openWaitMessage();
//////////////////////////////////////////////////////////////////////
// create a new ListRequest object and add the 'category' parameter //
//////////////////////////////////////////////////////////////////////
var listRequest = new ListRequest("lotatt-request");
/////////////////////////////////////
// create a new AjaxRequest object //
/////////////////////////////////////
var ajaxRequest = new AjaxRequest("/MyProject/services");
/////////////////////////////////////////
// send the list request to the server //
/////////////////////////////////////////
sendListRequest(ajaxRequest,listRequest,fillLotAtt,ajaxError);
}
HTML :
<div id="pleaseWait" style=" display: none; visibility: hidden; position:absolute; left:0px; top:0px; width:300px; height:200px; z-Index:999;">
<table border="1" cellspacing="0" cellpadding="0" width="100%">
<tr class="dialogHeaderCell" >
<td>
Please Wait...
</td>
</tr>
<tr>
<td align="center">
<img src="please_wait.gif" alt="Loading...Please wait.">
</td>
</tr>
</table>
</div>
<input type="button" name="DisplayInfo" class="secondary_button" value="Display Information " onClick="getInformation ()"/>
Please help, Thanks ahead
Sprenna, as you have mentioned you also have the option of using jQuery. If you want some kind of an in-depth read, then have a look at these three free jQuery books.
If you want a shorter introduction, have a look at this list of jQuery tutorials.
However, in short, using jQuery you can use this code to show/hide an HTML element:
$("#pleaseWait").show();
// or
$("#pleaseWait").hide();
# is an ID selector. So #foo selects an element that its ID is is foo.
Then you can use the jQuery offset function to position elements relative to the document.
Finally you can use jQuery width and height functions to set the size of your desired element(s).
I also recommend you to read Pro JavaScript Techniques by the creator of jQuery. It improves your JavaScript knowledge and skills significantly.
One possible cause is not appending the CSS unit when setting left and top programatically. Try this:
div.style.left = left + 'px';
div.style.top = top + 'px';
I created this jsfiddle so we can play with your code.

Automatic image resizing if browser width =

I asked this question today and got some great answers (thanks to the guys who helped me out there :) ).
Now please have a look at the following code. I'm a 100% sure the resizing part works, but my if/else statement doens't work (I'm still a JS rookie). I also mentioned this in my previous topic, but someone said I should rather post a new question.
(The script should detect someones browser width, so it can resize the #fluidimage)
note: the resizing part works. Only the viewportwidth detection and the if/else statement isnt functional yet.
$(window).load ( function () {
function resizer (index, measurement) {
var imageresize = 80;
var viewportWidth = width();
if ((viewportWidth >= 1680)) {
imageresize = 100;
} else if ((viewportWidth <= 1680) && (viewportWidth > 1280)) {
imageresize = 80;
} else if ((viewportWidth <= 1280) && (viewportWidth > 1024)) {
imageresize = 60;
} else if ((viewportWidth <= 1024) ) {
imageresize = 40;
} else {
imageresize = 100;
}
this.wCall = (typeof this.wCall == "null") ? true : this.wCall ^ true;
return this.wCall ? Math.round (measurement * imageresize / 100) : measurement;
}
$("#fluidimage").width (resizer).height (resizer);
} );
Change:
var viewportWidth = width();
To:
var viewportWidth = $(window).width();
See it at jsFiddle.

Categories

Resources