Caption text over an image - javascript

I am sorry, this a newbie question. I want to display random pictures taken from a directory of my server and I want to display a text associated to each image (txt files in the same directory. Example: 1.jpg -> 1.txt; 2.jpg -> 2.txt...). I want that the text appear above the image, in a frame placed on the top of the image, only upon mouse hover on the image.
The javascript code, css and html codes can be found here:
http://jsfiddle.net/Totoleheros/ES22a/
html code:
<img id="fullSize" onload="fixImage(this)" />
<div id="HOLDER">
<div id="theCaption"></div>
</div>
<img id="showImage" alt="random image" />
CSS code:
/* The first style is to hide the text*/
#theCaption {
position: absolute;
width: 200px;
height: 331px;
filter:alpha(opacity=0);
-moz-opacity:0;
-khtml-opacity: 0;
opacity: 0;
z-index: 3;
}
/*The send style is to show the text on hover*/
#theCaption:hover, #theCaption:active {
position: absolute;
width: 200px;
height: 40px;
background-color: #eeeeee;
color: #000000;
overflow: hidden;
font-family: arial;
font-weight: normal;
filter:alpha(opacity=80);
-moz-opacity:0.8;
-khtml-opacity: 0.8;
opacity: 0.8;
z-index: 3;
font-size: 10px;
line-height: 0.9em;
padding-top: 2px;
padding-right: 2px;
padding-bottom: 1px;
padding-left: 2px;
}
javascript code:
function fixImage(image) {
// I want an to display an image of 200x331px taken from a directory of image of various dimensions
var show = document.getElementById("showImage");
if (image.height > image.width) {
show.style.height = "331px";
show.style.width = Math.round((image.width / image.height) * 331) + "px";
} else {
show.style.width = "200px";
show.style.height = Math.round((image.height / image.width) * 200) + "px";
}
show.src = image.src;
show.style.visibility = "visible";
}
var MAXPICTURENUMBER = 166; // or whatever you choose
var rn = 1 + Math.floor(MAXPICTURENUMBER * Math.random());
// Here I point to the directory containing the images and the caption
var url = "http://www.test.fr/Images/RandomPictures/" + rn + ".jpg";
var caption = "http://www.test.fr/Images/RandomPictures/" + rn + ".txt";
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", caption, false);
xmlhttp.send();
captionText = xmlhttp.responseText;
window.onload = function () {
document.getElementById("theCaption").innerHTML = captionText;
document.getElementById("fullSize").src = url;
}
I am sure that there is a much cleaner/smarter solution than the one I am using, but remember, I'm a newbie.
My issue: this is almost working except that the text sometimes disappear according to the mouse position. How can I fix that?
Thkx in advance for your help!!

I would put the image and the caption in the same container. Something like
<div class="container">
<img class="image" src="image.png" />
<div class="caption">The caption</div>
</div>
and in css
.caption{position:relative; top:-20px; height:20px; display:none;}
.container:hover .caption{display:block;}
you can obviously style however.
EDIT: here's the final fiddle: http://jsfiddle.net/ES22a/5 part of the problem was a jQuery conflict so there's also a jQuery.noConflict(); in the head.

Related

appendTo adds element to another one, but it does not show on the website

I am trying to add arrows to my simple lightbox. The arrows are simple symbols "<" and ">. I have created them with jquery and when I try to add them to the image, they show up in the developer tools but not in the website for whatever reason. Can you tell me what's the problem please?
Here is the screenshot of the issue, if you did not understand my poor english. As you can see, the arrows are created in developer tools, but they cannot be found on the website. https://prnt.sc/26lyfbc
//Gallery Lightbox made with Jquery
let gallery = $('#gallery'),
overlay = $('<div = id = "overlay"></div>').appendTo('body').hide();
//Opens the lightbox with chosen image
gallery.find('a').on("click", function(event){
event.preventDefault();
let href = $(this).attr('href'),
image = $('<img>', {src: href}),
larrow = $('<div = id = "larrow"> < </div>'); //LEFT ARROW
rarrow = $('<div = id = "rarrow"> > </div>'); //RIGHT ARROW
image.appendTo(overlay);
larrow.appendTo(image);
overlay.show();
//Closes the Lightbox with the image, by clicking on the overlay
$(document).on("click", "#overlay", function(){
overlay.hide();
image.remove();
})
})
.gallery {
display: none;
opacity: 0;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-between;
width: 1004px;
margin: 0 auto;
}
.gallery img {
position: relative;
top: 100px;
height: 200px;
width: 300px;
margin: 0 1em;
}
#overlay {
background: rgba(0, 0, 0, .7);
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
text-align: center;
z-index: 10;
}
#overlay img {
margin-top: 5%;
border: solid 5px white;
border-radius: 5px;
}
//Dont mind these, the silly values are just for testing purposes
#larrow {
font-size: 500px;
color: red;
z-index: 2000;
}
#rarrow {
font-size: 500px;
color: red;
z-index: 2000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gallery" id="gallery">
<img src="img\placeholder1.jpg" alt="">
<img src="img\placeholder2.jpg" alt="">
<img src="img\placeholder3.jpg" alt="">
<img src="img\placeholder4.jpg" alt="">
<img src="img\placeholder5.jpg" alt="">
<img src="img\placeholder6.jpg" alt="">
</div>
</body>
You have a few errors in your code. Instead of
larrow = $('<div = id = "larrow"> < </div>'); //LEFT ARROW
rarrow = $('<div = id = "rarrow"> > </div>'); //RIGHT ARROW
You should write it like this. There is no need for the '=' between div and id.
larrow = $('<div id = "larrow"> < </div>'); //LEFT ARROW
rarrow = $('<div id = "rarrow"> > </div>'); //RIGHT ARROW
The same goes for the following tags:
overlay = $('<div id = "overlay"></div>').appendTo('body').hide();
Putting the div tags in the image will also not work. Instead you should put the image and the arrows in a container together like this:
<div id="overlay">
<img src ... </img>
<div id = "larrow"> < </div>
<div id = "rarrow"> > </div>
</div>
Refer to Floating Div Over An Image to see the needed css.

RotateY of a group of divs dynamically

I'm working on this script since 9 days, I found the script online, and from there I tried to add some code.
The point of the script is to rotate the Div dynamically based on the distance they have between each other.
In a way it works, if you resize the page at some point the divs turn their Y axes.
I have mainly 2 problems, the first one is that if I add new divs they just are shown in a new line.
The second problem is that those divs position should change, they need to get closer and they should move to the left side of the div.
I hope somebody can help because I spent already 10 days on this and I can't find a solution.
Thank you so much
function myFunction(distance) {
//add browser check currently it set for safari
// Code for Safari
var degree = 0;
if (distance <= -1 && distance >= -5) {
degree = 15;
} else if (distance < -5 && distance >= -10) {
degree = 25;
} else if (distance < -10 && distance >= -15) {
degree = 30;
} else if (distance < -15 && distance >= -20) {
degree = 35;
} else if (distance < -20) {
degree = 45;
}
document.getElementById("panel").style.WebkitTransform = "rotateY(" + degree + "deg)";
document.getElementById("panel2").style.WebkitTransform = "rotateY(" + degree + "deg)";
document.getElementById("panel3").style.WebkitTransform = "rotateY(" + degree + "deg)";
document.getElementById("panel4").style.WebkitTransform = "rotateY(" + degree + "deg)";
// document.getElementById("panel").style.marginRight= "100px";
document.getElementById("panel2").style.marginRight = "300px";
document.getElementById("panel3").style.marginRight = "30px";
document.getElementById("panel4").style.marginRight = "30px";
// document.getElementById("panel5").style.WebkitTransform = "rotateY(45deg)";
// document.getElementById("panel6").style.WebkitTransform = "rotateY(45deg)";
// Code for IE9
// document.getElementById("asd").style.msTransform = "rotateY(20deg)";
// Standard syntax
// document.getElementById("asd").style.transform = "rotateY(20deg)";
}
function myFunctionb() {
document.getElementById("panel").style.WebkitTransform = "rotateY(0deg)";
document.getElementById("panel2").style.WebkitTransform = "rotateY(0deg)";
document.getElementById("panel3").style.WebkitTransform = "rotateY(0deg)";
document.getElementById("panel4").style.WebkitTransform = "rotateY(0deg)";
// document.getElementById("panel5").style.WebkitTransform = "rotateY(0deg)";
// document.getElementById("panel6").style.WebkitTransform = "rotateY(0deg)";
}
// need to find a better solution
var first = document.getElementById("panel");
var second = document.getElementById("panel2");
var lastpanel = document.getElementById("panel4");
var lastbox = document.getElementById("last");
var container = document.getElementById("wrapper");
var notcongainer = container.offsetLeft;
var distance = container.offsetWidth - (lastpanel.offsetWidth + lastbox.offsetLeft + 4) + notcongainer;
console.log(distance);
var myVar;
var minDistance = 10;
function check() {
myVar = setInterval(testcheck, 100);
}
// First I check that the boxes lenght are as much as the container
// Then I check the distance between 2 boxes
function testcheck() {
if (distance < minDistance) {
myFunction(distance);
} else {
myFunctionb();
}
distance = container.offsetWidth - (lastpanel.offsetWidth + lastbox.offsetLeft + 4) + notcongainer;
/*console.log(distance)*/
}
//ADD NEW DIV
function addDiv() {
var div = document.createElement('div');
div.className = "col-box";
div.id = "newId";
div.innerHTML = '<div class="hover panel"><div id= "panel3" class="front"><div class="box1"><p>New Div</p></div></div></div>';
document.getElementById('wrapper').appendChild(div);
}
body {
background-color: #ecf0f1;
margin: 20px;
font-family: Arial, Tahoma;
font-size: 20px;
color: #666666;
text-align: center;
}
p {
color: #ffffff;
}
.col-box {
width: 22%;
position: relative;
display: inline;
display: inline-block;
margin-bottom: 20px;
z-index: 1;
}
.end {
margin-right: 0 !important;
}
/*-=-=-=-=-=-=-=-=-=-=- */
/* Flip Panel */
/*-=-=-=-=-=-=-=-=-=-=- */
.wrapper {
width: 80%;
height: 200px;
margin: 0 auto;
background-color: #bdd3de;
hoverflow: hidden;
border: 1px;
}
.panel {
margin: 0 auto;
height: 130px;
position: relative;
-webkit-perspective: 600px;
-moz-perspective: 600px;
}
.panel .front {
text-align: center;
}
.panel .front {
height: inherit;
position: absolute;
top: 0;
z-index: 900;
text-align: center;
-webkit-transform: rotateX(0deg) rotateY(0deg);
-moz-transform: rotateX(0deg) rotateY(0deg);
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-webkit-transition: all .4s ease-in-out;
-moz-transition: all .4s ease-in-out;
-ms-transition: all .4s ease-in-out;
-o-transition: all .4s ease-in-out;
transition: all .4s ease-in-out;
}
.panel.flip .front {
-webkit-transform: rotateY(45deg);
-moz-transform: rotateY(180deg);
}
.col-box:hover {
z-index: 1000;
}
.box1 {
background-color: #14bcc8;
width: 160px;
height: 60px;
margin-left: 5px;
padding: 20px;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}
<body onload="check()">
<div id="wrapper" class="wrapper">
<div id="first" class="col-box">
<div class="hover panel">
<div id="panel" class="front">
<div class="box1">
<p>Div 1</p>
</div>
</div>
</div>
</div>
<div id="second" class="col-box">
<div class="hover panel">
<div id="panel2" class="front">
<div class="box1">
<p>Div 2</p>
</div>
</div>
</div>
</div>
<div id="third" class="col-box">
<div class="hover panel">
<div id="panel3" class="front">
<div class="box1">
<p>Div 3</p>
</div>
</div>
</div>
</div>
<div id="last" class="col-box">
<div class="hover panel">
<div id="panel4" class="front">
<div class="box1">
<p>Last Div</p>
</div>
</div>
</div>
</div>
<button onclick="addDiv()">Add New Div</button>
</div>
9 days... that's too long. Time to step back and break this up into smaller things.
This isn't an 'answer' yet... but I need to post an image for you. Your question wasn't that clear, but it's not an easy thing to explain. In your case, I would show an image.
Now that I can see what you're doing - it doesn't sound like an arbitrary and completely silly task.
You have a list of 'things' or 'cards' or whatever... so, first things first... how do you insert new DOM into the page - and / into that list - and have the list all on one line. A few ways - but most likely you can just use flexbox -
https://jsfiddle.net/sheriffderek/8eLggama -> https://jsfiddle.net/sheriffderek/pztvhn3L (this is an example - but it's pretty naive - and the further you take this, the closer you'll get to building what most frameworks - like Vue could do way better... but good for learning! Start with something small - to just do that.
// will take an object with the list name and the card id
// eventuallly - you'd want the card to have more info sent in...
function addCard(infoObject) {
var targetList = document.getElementById(infoObject.list);
var li = document.createElement('li');
li.classList.add('item');
// ug! why aren't I using jQuery...
var component = document.createElement('aside');
component.classList.add('card');
var title = document.createElement('h2');
var uniqueId = idMaker.create();
var id = document.createTextNode(uniqueId);
title.appendChild(id);
component.appendChild(title)
li.appendChild(component);
targetList.appendChild(li);
// woah... this part is really boring...
// this is why templating engines and JSON are so popular
// you could also add 'remove' button etc... right?
var removeButton = document.createElement('button');
var removeText = document.createTextNode('x');
removeButton.appendChild(removeText);
removeButton.classList.add('remove-card');
component.appendChild(removeButton);
//
removeButton.addEventListener('click', function() {
var parent = document.getElementById(infoObject.list);
idMaker.removed.push(uniqueId);
parent.removeChild(li);
idMaker.read();
});
}
// start out with a few?
addCard({list: 'exampleTarget'});
addCard({list: 'exampleTarget'});
addCard({list: 'exampleTarget'});
// start a UI to add cards
var addCardButton = document.querySelector('[data-trigger="add-card"]');
addCardButton.addEventListener('click', function() {
addCard({list: 'exampleTarget'});
});
...and then you maybe absolute position the card inside of that list item? It's certainly a unique thing to do, and wont be easy. Then, you can check the number of items - of the width of each item - and make a calculation for transform based on that? Good luck!

Caption text over an image: not working anymore

This question is related to a previous post where the problem was temporarily solved: Caption text over an image.
I had to move my website to a new server where the script doesn't work anymore. The purpose is to load a random image from a folder on my website and to display over the image a related paired text (image1.jpg & text1.txt).
After the migration of the site, nor the images or the text would display. I could get the image displayed again by changing this line of code:
xmlhttp.open("GET", caption, false);
->
xmlhttp.open("GET", caption, true);
This has fixed the problem of the images but the attached text is still not displayed.
The updated JSfiddle is there: http://jsfiddle.net/Totoleheros/ES22a/7/.
html:
<img class="fullSize" onload="fixImage(this)" />
<div class="HOLDER">
<div class="theCaption"></div>
<img id="showImage" alt="random image" />
</div>
javascript:
function fixImage( image )
{
// change calculations to match your needs
var show = document.getElementById("showImage");
if ( image.height > image.width )
{
show.style.height = "331px";
show.style.width = Math.round( (image.width / image.height) * 331 ) + "px";
} else {
show.style.width = "200px";
show.style.height = Math.round( (image.height / image.width) * 200 ) + "px";
}
show.src = image.src;
show.style.visibility = "visible";
}
var MAXPICTURENUMBER = 166; // or whatever you choose
var rn = 1 + Math.floor( MAXPICTURENUMBER * Math.random() );
var url ="http://www.lvts.fr/Images/RandomPictures/" + rn + ".jpg";
var caption ="http://www.lvts.fr/Images/RandomPictures/" + rn + ".txt";
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", caption, true);
xmlhttp.send();
window.onload = function() { jq('.theCaption').html(xmlhttp.responseText); jq('.fullSize').prop('src',url); };
$mirage(document).ready(function(){
$mirage('body').unbind('mouseenter');
var mirageMenuConfig = { sensitivity: 3, interval: 30, over: revealMainMenuChildren, timeout: 500, out: hideMainMenuChildren };
function revealMainMenuChildren(){ $mirage(this).children("ul").css('opacity','1').slideDown(300); }
function hideMainMenuChildren(){ $mirage(this).children("ul").fadeTo(300, 0).slideUp(300); }
$mirage("#nav ul ul").parent().addClass("ddarrow");
$mirage("#nav ul ul").parent().append("<span></span>");
$mirage("#nav ul ul").css({ display: "none" });
$mirage("#nav ul li").hoverIntent(mirageMenuConfig);
});
CSS:
#showImage {
display: block;
height: 331px; width: 200px;
visibility: hidden;
z-index: 1;
}
.HOLDER {
position: relative;
width:200px;
margin:0 auto;
}
.theCaption {
position: absolute;
width: 196px; height: 40px;
background-color: #eeeeee; color: #000000;
overflow: hidden;
font-family: arial; font-weight: normal;
filter:alpha(opacity=80);
-moz-opacity:0.8;
-khtml-opacity: 0.8;
opacity: 0.8;
z-index: 2;
font-size: 10px;
line-height: 0.9em;
padding-top: 2px;
padding-right: 2px;
padding-bottom: 1px;
padding-left: 2px;
display: none;
}
.HOLDER:hover .theCaption {display:block;}
.fullSize {
position: absolute;
top: 0px; left: 0px;
visibility: hidden;
}
I don't understand why moving the website has generated this issue. Any help would be very much appreciated...
That's because the speed of the connection to the server changed - it got slower.
AJAX request are asynchronous. What happens is that you send the request, read the result and then the response from the server comes in. Use this code instead:
var caption ="http://www.lvts.fr/Images/RandomPictures/" + rn + ".txt";
$( document ).ready(function() {
$.ajax(caption, {
dataType: 'html',
success: function(data, textStatus, jqXHR) {
console.log('data', data);
$('.theCaption').html(data);
}
});
$('.fullSize').prop('src',url);
});
jQuery will prepare everything to call the success callback when the server response comes in. See http://learn.jquery.com/ajax/
And you should use $( document ).ready(); instead of window.onload
Note: For this to work, the document must be served from www.lvts.fr as well or you'll get this error:
XMLHttpRequest cannot load http://www.lvts.fr/Images/RandomPictures/79.txt. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.

Progress bar with slide ability

I am new to JavaScript/CSS (basically the whole world of web dev) and I am really struggling to create the following widget. I created a picture of what I want to make to make it more clear.
The Play/Pause and Stop button are ready. Loop checkbox is no problem. But the progress bar is painful. The two markers are supposed to mark the point from where the file would start playing and where it would stop. The progress bar is also supposed to be click-able, so if I want to access a certain point in time, then its possible.
What I tried so far
jQuery UI slider: For a sliding progress bar and use that draggable slider to access a certain point in audio file. Works fine. But no markers and looks really ugly. Don't how to change it.
<progress> tag: not very flexible. Marker? Clicking?
<div> tag: there seems to be no way to get the point where I clicked.
So, what do you guys recommend? How should I proceed?
Canvas Alternative
You might want to use a canvas and draw your own progress bar element within it.
Here are some canvas progress bar tutorials:
How to create a progress bar with HTML5
A progress bar using HTML5 canvas
Doing it with <progress>
To access the clicked position within a DOMElement, you can proceed with the click event's properties: clientX and clientY (MDN Source), like so:
HTML
<div class="marker" id="StartMarker">^</div>
<div class="marker" id="StopMarker">^</div>
<progress id="progress" value="0" min="0" max="100">0%</progress>
<form id="choice">
<button id="marker1">Beginning marker</button>
<button id="marker2">Ending marker</button>
<input type="hidden" id="markerValue" value="0" />
</form>
JavaScript (not optimized)
document.getElementById('progress').onclick = function (event, element) {
/* Math.floor((event.offsetX / this.offsetWidth) * 100) */
var newProgress = event.offsetX;
document.getElementById('choice').style.display = "block";
document.getElementById('markerValue').setAttribute('value', newProgress);
document.getElementById('marker1').onclick = function (event) {
event.preventDefault();
var newProgress = document.getElementById('markerValue').value;
var progressBar = document.getElementById('progress');
var startMarker = document.getElementById('StartMarker');
var stopMarker = document.getElementById('StopMarker');
var marker = startMarker;
marker.style.display = "block";
startMarker.style.display = "block";
startMarker.offsetTop = (progressBar.offsetTop + progressBar.offsetHeight + 2) + "px";
startMarker.style.left = newProgress + "px";
};
document.getElementById('marker2').onclick = function (event) {
event.preventDefault();
var newProgress = document.getElementById('markerValue').value;
var progressBar = document.getElementById('progress');
var startMarker = document.getElementById('StartMarker');
var stopMarker = document.getElementById('StopMarker');
stopMarker.style.display = "block";
stopMarker.offsetTop = (progressBar.offsetTop + progressBar.offsetHeight + 2) + "px";
stopMarker.style.left = newProgress + "px";
};
};
CSS
.marker {
position:absolute;
top:24px;
left:9px;
display:none;
z-index:8;
font-weight:bold;
text-align:center;
}
#StartMarker {
color: #CF0;
}
#StopMarker {
color:#F00;
}
#choice {
display:none;
}
progress {
display: inline-block;
-moz-box-sizing: border-box;
box-sizing: border-box;
width: 300px;
height: 20px;
padding: 3px 3px 2px 3px;
background: #333;
background: -webkit-linear-gradient(#2d2d2d, #444);
background: -moz-linear-gradient(#2d2d2d, #444);
background: -o-linear-gradient(#2d2d2d, #444);
background: linear-gradient(#2d2d2d, #444);
border: 1px solid rgba(0, 0, 0, .5);
border-radius: 15px;
box-shadow: 0 1px 0 rgba(255, 255, 255, .2);
}
Live Demo
Using simple blocks for that is possible. Your layout would look like this (simplified):
HTML
<div class="progressbar">
<div class="bar">
<div class="progress" style="width: 30%;">
</div>
</div>
<div class="markers">
<div class="right" style="width: 70%;">
<div class="marker">
</div>
<div class="left" style="width: 20%;">
<div class="marker">
</div>
</div>
</div>
</div>
</div>
SCSS
.progressbar {
width: 20em;
background: grey;
.bar {
height: 2em;
.progress {
background: blue;
height: 100%;
}
}
.markers {
height: 1em;
background: white;
.right {
height: 100%;
background: red;
.marker {
width: 1em;
height: 100%;
background: green;
position: relative;
float: right;
}
.left {
background: white;
height: 100%;
}
}
}
}
The operations can be quite difficult
jQuery
$('.bar').click(function(e){
$(this).find('.progress').css('width', (e.offsetX / this.offsetWidth)*100+'%');
});
will set the Progressbar properly on clicks.
For the markers though you will need mousedown, mousemove, mouseleave events, since you got 2 of them.
Example
http://jsfiddle.net/JXauW/

how do I center javascript css popup div, no matter what the screen resolution?

I have the following code that opens a new popup window while disabling the background, the problem is that I have to position this so that it's 100px from the top (already got that through the CSS #dialog) and also in the center of the screen, no matter what the user's resolution is?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function showPopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "1024"
cvr.style.height = "100%"
}
}
function closePopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "none"
dlg.style.display = "none"
document.body.style.overflowY = "scroll"
}
</script>
<style type="text/css">
#cover {
display: none;
position: absolute;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
background: gray;
filter: alpha(Opacity = 50);
opacity: 0.5;
-moz-opacity: 0.5;
-khtml-opacity: 0.5
}
#dialog {
display: none;
left: 100px;
top: 100px;
width: 300px;
height: 300px;
position: absolute;
z-index: 100;
background: white;
padding: 2px;
font: 10pt tahoma;
border: 1px solid gray
}
</style>
</head>
<body>
<div id="cover"></div>
<div id="dialog">
My Dialog Content
<br><input type="text">
<br><input type="button" value="Submit">
<br>[Close]
</div>
Show
</body>
</html>
CSS based solution to center:
You need to use these styles to make it appear dead-center:
position:absolute;
top:50%;
left:50%;
width:400px; /* adjust as per your needs */
height:400px; /* adjust as per your needs */
margin-left:-200px; /* negative half of width above */
margin-top:-200px; /* negative half of height above */
So position should be specified. The top and left should be 50%. The margin-left and margin-top should be negative one half of the width and height of the box respectively.
Notice that if you want your popup to appear on center even when page is scrolled you will have to use position:fixed instead with the draw back that it doesn't work in IE6.
Just do this:
.body {
position: relative;
}
.popup {
position: absolute;
max-width: 800px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
no matters the screen or popup size. This will center the <div class="popup"></div>.
What you need is called a light-box.
To create it you should modify HTML,CSS and JS code.
Let's say your lightbox consist only of the string "login form". (You can put everything you want there) The HTML code should look like this:
<div id = "loginBox">login form</div>
Now, we need to hide it with CSS:
div#loginBox {
display: none;
}
Now our box is not visible. Lets modify our box as you want it to be 100px from the top:
div#loginBox {
display: none;
top: 100px;
}
We will worry about disabling the background later.
Our next job is to make a button that will display the box when we need it. Easy-peasy:
<div id = "loginBox" >login form</div>
<a id = "displayButton">login</a>
Note that we don't need the "href" attribute, because that will move the screen on clicking and other unwanted behavior.
Let's attach event handler on the button via JS:
var IE = document.all ? true : false; // obligatory "browser sniffing"
function display_box() {
document.getElementsById("loginBox").style.display = "inline-block"; // or "inline"
}
window.onload = function() {
var login_box = document.getElementsById("loginBox");
if (!IE) {
login_box.addEventListener( "click", display_box , false );
}
else {
login_box.attachEvent( "onclick", display_box );
}
}
But you want it to be in the center of the screen? Then the function goes like this:
function display_box() {
var theBox = document.getElementsById("loginBox").style,
left = document.width / 2 - 50; // 150 because it is 300 / 2
theBox.display = "inline-block";
theBox.left = left.toString() + "px";
}
I would guess that you will want to close the window at some point and make the "disabled background" effect. To do so you can create a div class that extends on the whole screen, attach a "display" event on it, put some z-index in the css to be sure the loginBox is over the "disabled background", and attach a "close the loginBox" event on the "background" div. And now the final code looks like this:
Note that we care only about the placement of the login-button, because the other are hidden from view, and then modified by JS:
HTML:
<div id = "loginBox" >login</div>
<a id = "displayButton">login</a>
<div id = "backgroundDarkener"> </div>
CSS:
div#loginBox {
display: none;
top: 100px;
width: 300px; #it is important to know the width of the box, to center it correctly
z-index: 2;
}
div#backgroundDarkener {
background: #000;
display: none;
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
z-index: 1;
opacity: 0.8;
# needless to say, you should play with opacity or if you want your
# css to validate - background image (because I suspect it won't
# validate for old versions of IE, Safari, etc.) This is just a suggestion
}
JS:
var IE = document.all ? true : false; // obligatory "browser sniffing"
function display_box() {
var theBox = document.getElementsById("loginBox").style,
background = document.getElementsById("loginBox").style,
left = document.width / 2 - 150; // 150 is 300 / 2
theBox.display = "inline-block";
theBox.left = left.toString() + "px";
background.display = "inline-block";
}
function hide_box() {
document.getElementsById("loginBox").style.display = "none";
document.getElementsById("backgroundDarkener").style.display = "none";
}
window.onload = function() {
var login_box = document.getElementsById("loginBox"),
background = document.getElementsById("backgroundDarkener");
if (!IE) {
login_box.addEventListener( "click", display_box , false );
background.addEventListener( "click", hide_box , false );
}
else {
login_box.attachEvent( "onclick", display_box );
background.attachEvent( "onclick", hide_box );
}
}
A quick Google search found this;
function PopupCenter(pageURL, title,w,h) {
var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}
This is where flexbox comes rescue now!
.parent {
display: flex;
height: 300px; /* Or whatever */
}
.child {
width: 100px; /* Or whatever */
height: 100px; /* Or whatever */
margin: auto; /* Magic! */
}
You need to use these styles to make div center:
width:500px;
left:0;
right:0;
margin:0 auto;
Simple, margin: 100px auto;. There's no need to do calculations in JavaScript.
Live Example

Categories

Resources