adding text to overlay in javascript - javascript

I've used some source for a transparent overlay in JavaScript:
function grayOut(vis, options)
{
var options = options || {};
var zindex = 50;
var opacity = 70;
var opaque = (opacity / 100);
var bgcolor = options.bgcolor || '#000000';
var dark=document.getElementById('darkenScreenObject');
if (!dark) {
// The dark layer doesn't exist, it's never been created. So we'll
// create it here and apply some basic styles.
// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
var tbody = document.getElementsByTagName("body")[0];
var tnode = document.createElement('div'); // Create the layer.
tnode.style.position='absolute'; // Position absolutely
tnode.style.top='0px'; // In the top
tnode.style.left='0px'; // Left corner of the page
tnode.style.display='none'; // Start out Hidden
tnode.id='darkenScreenObject'; // Name it so we can find it later
tbody.appendChild(tnode);
/*
var pTag = document.createElement("P");
var txtProcessing = document.createTextNode("Processing GIF...");
tnode.appendChild(txtProcessing);
*/
}
if (vis)
{
// Calculate the page width and height
if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) )
{
var pageWidth = document.body.scrollWidth+'px';
var pageHeight = document.body.scrollHeight+'px';
}
else if( document.body.offsetWidth )
{
var pageWidth = document.body.offsetWidth+'px';
var pageHeight = document.body.offsetHeight+'px';
}
else
{
var pageWidth='100%';
var pageHeight='100%';
}
//set the shader to cover the entire page and make it visible.
dark.style.opacity=opaque;
dark.style.MozOpacity=opaque;
dark.style.filter='alpha(opacity='+opacity+')';
dark.style.zIndex=zindex;
dark.style.backgroundColor=bgcolor;
dark.style.width= pageWidth;
dark.style.height= pageHeight;
dark.style.display='block';
var txt = document.createTextNode("This text was added.");
dark.appendChild(txt);
}
else
{
dark.style.display='none';
}
}
My problem is I'm trying to get some text to show up on the transparent layer but I can't get it to work. Any thoughts?

Your text node is created on overlay but is invisible cause of text color.
check Fiddle where text color is set to red.
dark.style.color = 'red';

Related

How do I remove setInterval from progress bar in Javascript and make appear the VerticalBar instantaneously?

I have the classical Progress bar in Javascript. I Would like to simply place the vertical bar without seeing it moving on the screen.
function progressbar() {
var vertical_bar2 = document.querySelector("#P5 .vl5");
var element = document.getElementById("myprogressBar");
var ValueSet = 25
var width = 0;
document.getElementById("vl5").style.display='';
document.getElementById("value2").style.display='';
document.getElementById("value1").style.display='';
var identity = setInterval(scene, 10);
function scene() {
if (width >= ValueSet) {
clearInterval(identity);
} else {
width++;
vertical_bar2.style.left = `${width}%`;
document.getElementById("value2").innerHTML = ValueSet
}
}
}
I am trying the following script but it is not working
function progressbar() {
var vertical_bar2 = document.querySelector("#P5 .vl5");
var element = document.getElementById("progressBar");
var CE = 25
var width = 0;
document.getElementById("vl5").style.display='';
document.getElementById("Value2").style.display='';
document.getElementById("Value1").style.display='';
vertical_bar2.style.left = 25;
document.getElementById("Value").innerHTML = CE
}
Based on the code your provided, it looks like you just need to set a unit for the left property of your bar. Currently you are only setting a value (25), but without a unit (%, px, em, etc.) it will not apply anything.
vertical_bar2.style.left = "25%";
or
vertical_bar2.style.left = `${CE}%`;

I have a script to resize an image. Is there anyway to have it output 5 images?

doc = app.activeDocument;
// these are our values for the END RESULT width and height (in pixels) of our image
var fWidth = 1313;
var fHeight = 1750;
// do the resizing. if height > width (portrait-mode) resize based on height. otherwise, resize based on width
if (doc.height > doc.width) {
doc.resizeImage(null,UnitValue(fHeight,"px"),null,ResampleMethod.BICUBIC);
}
else {
doc.resizeImage(UnitValue(fWidth,"px"),null,null,ResampleMethod.BICUBIC);
}
// Makes the default background white
var white = new SolidColor();
white.rgb.hexValue = "FFFFFF";
app.backgroundColor = white;
// 2012, use it at your own risk;
#target photoshop
if (app.documents.length > 0) {
var myDocument = app.activeDocument;
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PERCENT;
myDocument.resizeCanvas(myDocument.width + 40, myDocument.height + 40, AnchorPosition.MIDDLECENTER)
app.preferences.rulerUnits = originalRulerUnits;
};
// our web export options
var options = new ExportOptionsSaveForWeb();
options.quality = 70;
options.format = SaveDocumentType.JPEG;
options.optimized = true;
var newName = 'test'+doc.name+'.jpg';
doc.exportDocument(File(doc.path+'/'+newName),ExportType.SAVEFORWEB,options);
I want to be able to generate 5 images with 5 different sizes with the same script. Is it just as simple as repeating my code multiple times, or do i need to reset some variables in between?
When I try just duplicating my code and changing the output file name and the sizes, it does it but my canvas size doesn't reset and change based off the current image size. It just keeps getting bigger. Is there anyway to make the canvas size resize based on that current image size?
var sizes = [
{
width: 1531,
height: 1948
},
{
width: 1303,
height: 1954
},
{
width: 1066,
height: 1909
}
];
doc = app.activeDocument;
// looping through all the sizes
for (var i = 0; i < sizes.length; i++)
{
var cloneDoc = doc.duplicate(); // duplicates current document
resizeAndSave(sizes[i].width, sizes[i].height); // passes width and height of sizes to function with your code
cloneDoc.close(SaveOptions.DONOTSAVECHANGES); // closes the clone
activeDocument = doc; // making sure that foremost document is the original doc
}
function resizeAndSave(fWidth, fHeight)
{
//your code
// get a reference to the current (active) document and store it in a variable named "doc"
// these are our values for the END RESULT width and height (in pixels) of our image
//var fWidth = 1313;
//var fHeight = 1750;
// do the resizing. if height > width (portrait-mode) resize based on height. otherwise, resize based on width
activeDocument = doc;
if (doc.height > doc.width) {
doc.resizeImage(null,UnitValue(fHeight,"px"),null,ResampleMethod.BICUBIC);
}
else {
doc.resizeImage(UnitValue(fWidth,"px"),null,null,ResampleMethod.BICUBIC);
}
// Makes the default background white
var white = new SolidColor();
white.rgb.hexValue = "FFFFFF";
app.backgroundColor = white;
// 2012, use it at your own risk;
#target photoshop
if (app.documents.length > 0) {
var myDocument = app.activeDocument;
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PERCENT;
myDocument.resizeCanvas(myDocument.width + 40, myDocument.height + 40, AnchorPosition.MIDDLECENTER)
app.preferences.rulerUnits = originalRulerUnits;
};
// our web export options
var options = new ExportOptionsSaveForWeb();
options.quality = 70;
options.format = SaveDocumentType.JPEG;
options.optimized = true;
var newName = 'test'+doc.name+'.jpg';
doc.exportDocument(File(doc.path+'/'+newName),ExportType.SAVEFORWEB,options);
};
You need to reset or clone your original document in the beginning of the each loop. I prefer cloning so I'd do something like this:
// creating array of sizes
var sizes = [
{
width: 313,
height: 750
},
{
width: 413,
height: 150
}, ];
// looping through all the sizes
for (var i = 0; i < sizes.length; i++)
{
var cloneDoc = doc.duplicate(); // duplicates current document
resizeAndSave(sizes[i].width, sizes[i].height); // passes width and height of sizes to function with your code
cloneDoc.close(SaveOptions.DONOTSAVECHANGES); // closes the clone
activeDocument = doc; // making sure that foremost document is the original doc
}
function resizeAndSave(fWidth, fHeight)
{
//your code
};
doc = app.activeDocument;
var savedState = app.activeDocument.activeHistoryState
// get a reference to the current (active) document and store it in a variable named "doc"
// these are our values for the END RESULT width and height (in pixels) of our image
var fWidth = 1155;
var fHeight = 1471;
// do the resizing. if height > width (portrait-mode) resize based on height. otherwise, resize based on width
activeDocument = doc;
if (doc.height > doc.width) {
doc.resizeImage(null,UnitValue(fHeight,"px"),null,ResampleMethod.BICUBIC);
}
else {
doc.resizeImage(UnitValue(fWidth,"px"),null,null,ResampleMethod.BICUBIC);
}
// Makes the default background white
var white = new SolidColor();
white.rgb.hexValue = "FFFFFF";
app.backgroundColor = white;
// 2012, use it at your own risk;
#target photoshop
if (app.documents.length > 0) {
activeDocument = doc;
var cwidth = 2000;
var cheight = 2000;
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
doc.resizeCanvas(cwidth, cheight, AnchorPosition.MIDDLECENTER)
app.preferences.rulerUnits = originalRulerUnits;
};
// our web export options
var options = new ExportOptionsSaveForWeb();
options.quality = 70;
options.format = SaveDocumentType.JPEG;
options.optimized = true
var newName = 'MIR'+doc.name +'-22_28'+'.jpg';
doc.exportDocument(File(doc.path+'/'+newName),ExportType.SAVEFORWEB,options);
app.activeDocument.activeHistoryState = savedState
// these are our values for the END RESULT width and height (in pixels) of our image
var hWidth = 1141;
var hHeight = 1711;
// do the resizing. if height > width (portrait-mode) resize based on height. otherwise, resize based on width
activeDocument = doc;
if (doc.height > doc.width) {
doc.resizeImage(null,UnitValue(hHeight,"px"),null,ResampleMethod.BICUBIC);
}
else {
doc.resizeImage(UnitValue(hWidth,"px"),null,null,ResampleMethod.BICUBIC);
}
// Makes the default background white
var white = new SolidColor();
white.rgb.hexValue = "FFFFFF";
app.backgroundColor = white;
// 2012, use it at your own risk;
#target photoshop
if (app.documents.length > 0) {
activeDocument = doc;
var cwidth = 2000;
var cheight = 2000;
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
doc.resizeCanvas(cwidth, cheight, AnchorPosition.MIDDLECENTER)
app.preferences.rulerUnits = originalRulerUnits;
};
// our web export options
var options = new ExportOptionsSaveForWeb();
options.quality = 70;
options.format = SaveDocumentType.JPEG;
options.optimized = true;
var newName = 'MIR'+doc.name+'-24_36'+'.jpg';
doc.exportDocument(File(doc.path+'/'+newName),ExportType.SAVEFORWEB,options);
app.activeDocument.activeHistoryState = savedState
// these are our values for the END RESULT width and height (in pixels) of our image
var fWidth = 1058;
var fHeight = 1897;
// do the resizing. if height > width (portrait-mode) resize based on height. otherwise, resize based on width
activeDocument = doc;
if (doc.height > doc.width) {
doc.resizeImage(null,UnitValue(fHeight,"px"),null,ResampleMethod.BICUBIC);
}
else {
doc.resizeImage(UnitValue(fWidth,"px"),null,null,ResampleMethod.BICUBIC);
}
// Makes the default background white
var white = new SolidColor();
white.rgb.hexValue = "FFFFFF";
app.backgroundColor = white;
// 2012, use it at your own risk;
#target photoshop
if (app.documents.length > 0) {
activeDocument = doc;
var cwidth = 2000;
var cheight = 2000;
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
doc.resizeCanvas(cwidth, cheight, AnchorPosition.MIDDLECENTER)
app.preferences.rulerUnits = originalRulerUnits;
};
// our web export options
var options = new ExportOptionsSaveForWeb();
options.quality = 70;
options.format = SaveDocumentType.JPEG;
options.optimized = true;
var newName = 'MIR'+doc.name+'-24_43'+'.jpg';
doc.exportDocument(File(doc.path+'/'+newName),ExportType.SAVEFORWEB,options);
app.activeDocument.activeHistoryState = savedState
// these are our values for the END RESULT width and height (in pixels) of our image
var fWidth = 1360;
var fHeight = 1813;
// do the resizing. if height > width (portrait-mode) resize based on height. otherwise, resize based on width
activeDocument = doc;
if (doc.height > doc.width) {
doc.resizeImage(null,UnitValue(fHeight,"px"),null,ResampleMethod.BICUBIC);
}
else {
doc.resizeImage(UnitValue(fWidth,"px"),null,null,ResampleMethod.BICUBIC);
}
// Makes the default background white
var white = new SolidColor();
white.rgb.hexValue = "FFFFFF";
app.backgroundColor = white;
// 2012, use it at your own risk;
#target photoshop
if (app.documents.length > 0) {
activeDocument = doc;
var cwidth = 2000;
var cheight = 2000;
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
doc.resizeCanvas(cwidth, cheight, AnchorPosition.MIDDLECENTER)
app.preferences.rulerUnits = originalRulerUnits;
};
// our web export options
var options = new ExportOptionsSaveForWeb();
options.quality = 70;
options.format = SaveDocumentType.JPEG;
options.optimized = true;
var newName = 'MIR'+doc.name+'-30_40'+'.jpg';
doc.exportDocument(File(doc.path+'/'+newName),ExportType.SAVEFORWEB,options);
app.activeDocument.activeHistoryState = savedState
// get a reference to the current (active) document and store it in a variable named "doc"

Dynamically Adjusting an element with javascript or JQuery

I want to dynamically adjust the position of a YouTube video element using javascript based on the browser dimensions. I am not looking for a purely CSS Solution, I know that I can do that with padding, I am looking for a javascript solution which alters CSS of the div.
In this instance my DIV is "wrappervideo"
<script>
var viewWidth = window.innerWidth;
var viewHeight = window.innerHeight;
var narrowPadding = (((viewWidth/1.7777)-(viewHeight/1.5))/2);
var tallHeight = (viewHeight/1.5);
var tallWidth = (viewHeight/1.5)*1.7777;
var tallPadding = ((viewWidth)-(viewHeight/1.5)1.7777)/2;
function findAspectRatio() {
if ( viewWidth/(viewHeight/1.5) >= 1.777) {
setTimeout(narrow,0)}
if ( viewWidth/(viewHeight/1.5) <= 1.777) {
setTimeout(tall,0)}
if ( viewWidth/(viewHeight/1.5) == 1.777) {
setTimeout(equal,0)}
}
function equal() {
wrappervideo.style.top = '0px';
wrappervideo.style.width = '100%'; }
function narrow() {
wrappervideo.style.top = narrowPadding;
wrappervideo.style.width = '100%'; }
function tall() {
wrappervideo.style.right = tallPadding;
wrappervideo.style.width = tallWidth; }
</script>
Edited - This is what I have currently. Any thoughts on why this isn't working?

why this javascript code don't work after i reload part of my page with ajax?

I have 3 files with php and js. in first file i load some information and show it to user, then user can change them. for show other information to user i reload part of my page with some code that they are in second php file. i put them in <div id='show_album'>my data</div> and change them with second php file.
for first run my javascript code work fine, but after reloading part of page it never work. what must i change in code that it work after reloading?!
this is part of code that can reload div element with ajax:
<select onchange="showList('showalbum.php?change=',this.value,'show_album')"><option value='1'>1</option> <option value='2'>2</option></select>
in this part of code that in first page i reload my div element with new data.
then in new data i have something like this:
size of picture: 460*345
that show picture link to user and when user click on it, with javascript i show it to user on this page and on my other information that user can close it.but now this rel="lightbox" don't work and when user click on link, this picture open in same window.
this is my javascript code and in <head> i define it:
/*
Table of Contents
-----------------
Configuration
Functions
- getPageScroll()
- getPageSize()
- pause()
- getKey()
- listenKey()
- showLightbox()
- hideLightbox()
- initLightbox()
- addLoadEvent()
Function Calls
- addLoadEvent(initLightbox)
*/
//
// Configuration
//
// If you would like to use a custom loading image or close button reference them in the next two lines.
var loadingImage = './LightBox/loading.gif';
var closeButton = './LightBox/close.gif';
//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){
var yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
} else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
}
arrayPageScroll = new Array('',yScroll)
return arrayPageScroll;
}
//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
xScroll = document.body.scrollWidth;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight) { // all except Explorer
windowWidth = self.innerWidth;
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if(yScroll < windowHeight){
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}
// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){
pageWidth = windowWidth;
} else {
pageWidth = xScroll;
}
arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
return arrayPageSize;
}
//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
var now = new Date();
var exitTime = now.getTime() + numberMillis;
while (true) {
now = new Date();
if (now.getTime() > exitTime)
return;
}
}
//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
key = String.fromCharCode(keycode).toLowerCase();
if(key == 'x'){ hideLightbox(); }
}
//
// listenKey()
//
function listenKey () { document.onkeypress = getKey; }
//
// showLightbox()
// Preloads images. Pleaces new image in lightbox then centers and displays.
//
function showLightbox(objLink)
{
// prep objects
var objOverlay = document.getElementById('overlay');
var objLightbox = document.getElementById('lightbox');
var objCaption = document.getElementById('lightboxCaption');
var objImage = document.getElementById('lightboxImage');
var objLoadingImage = document.getElementById('loadingImage');
var objLightboxDetails = document.getElementById('lightboxDetails');
var arrayPageSize = getPageSize();
var arrayPageScroll = getPageScroll();
// center loadingImage if it exists
if (objLoadingImage) {
objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
objLoadingImage.style.display = 'block';
}
// set height of Overlay to take up whole page and show
objOverlay.style.height = (arrayPageSize[1] + 'px');
objOverlay.style.display = 'block';
// preload image
imgPreload = new Image();
imgPreload.onload=function(){
objImage.src = objLink.href;
// center lightbox and make sure that the top and left values are not negative
// and the image placed outside the viewport
var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - imgPreload.height) / 2);
var lightboxLeft = ((arrayPageSize[0] - 20 - imgPreload.width) / 2);
objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
objLightboxDetails.style.width = imgPreload.width + 'px';
if(objLink.getAttribute('title')){
objCaption.style.display = 'block';
//objCaption.style.width = imgPreload.width + 'px';
objCaption.innerHTML = objLink.getAttribute('title');
} else {
objCaption.style.display = 'none';
}
// A small pause between the image loading and displaying is required with IE,
// this prevents the previous image displaying for a short burst causing flicker.
if (navigator.appVersion.indexOf("MSIE")!=-1){
pause(250);
}
if (objLoadingImage) { objLoadingImage.style.display = 'none'; }
objLightbox.style.display = 'block';
// After image is loaded, update the overlay height as the new image might have
// increased the overall page height.
arrayPageSize = getPageSize();
objOverlay.style.height = (arrayPageSize[1] + 'px');
// Check for 'x' keypress
listenKey();
return false;
}
imgPreload.src = objLink.href;
var e = document.getElementById('gand');
e.style.display = 'none';
}
//
// hideLightbox()
//
function hideLightbox()
{
// get objects
objOverlay = document.getElementById('overlay');
objLightbox = document.getElementById('lightbox');
// hide lightbox and overlay
objOverlay.style.display = 'none';
objLightbox.style.display = 'none';
// disable keypress listener
document.onkeypress = '';
var e = document.getElementById('gand');
e.style.display = 'block';
}
//
// initLightbox()
// Function runs on window load, going through link tags looking for rel="lightbox".
// These links receive onclick events that enable the lightbox display for their targets.
// The function also inserts html markup at the top of the page which will be used as a
// container for the overlay pattern and the inline image.
//
function initLightbox()
{
if (!document.getElementsByTagName){ return; }
var anchors = document.getElementsByTagName("a");
// loop through all anchor tags
for (var i=0; i<anchors.length; i++){
var anchor = anchors[i];
if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox")){
anchor.onclick = function () {showLightbox(this); return false;}
}
}
// the rest of this code inserts html at the top of the page that looks like this:
//
// <div id="overlay">
// <img id="loadingImage" />
// </div>
// <div id="lightbox">
// <a href="#" onclick="hideLightbox(); return false;" title="Click anywhere to close image">
// <img id="closeButton" />
// <img id="lightboxImage" />
// </a>
// <div id="lightboxDetails">
// <div id="lightboxCaption"></div>
// <div id="keyboardMsg"></div>
// </div>
// </div>
var objBody = document.getElementsByTagName("body").item(0);
// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
var objOverlay = document.createElement("div");
objOverlay.setAttribute('id','overlay');
objOverlay.onclick = function () {hideLightbox(); return false;}
objOverlay.style.display = 'none';
objOverlay.style.position = 'absolute';
objOverlay.style.top = '0';
objOverlay.style.left = '0';
objOverlay.style.zIndex = '90';
objOverlay.style.width = '100%';
objBody.insertBefore(objOverlay, objBody.firstChild);
var arrayPageSize = getPageSize();
var arrayPageScroll = getPageScroll();
// preload and create loader image
var imgPreloader = new Image();
// if loader image found, create link to hide lightbox and create loadingimage
imgPreloader.onload=function(){
var objLoadingImageLink = document.createElement("a");
objLoadingImageLink.setAttribute('href','#');
objLoadingImageLink.onclick = function () {hideLightbox(); return false;}
objOverlay.appendChild(objLoadingImageLink);
var objLoadingImage = document.createElement("img");
objLoadingImage.src = loadingImage;
objLoadingImage.setAttribute('id','loadingImage');
objLoadingImage.style.position = 'absolute';
objLoadingImage.style.zIndex = '150';
objLoadingImageLink.appendChild(objLoadingImage);
imgPreloader.onload=function(){}; // clear onLoad, as IE will flip out w/animated gifs
return false;
}
imgPreloader.src = loadingImage;
// create lightbox div, same note about styles as above
var objLightbox = document.createElement("div");
objLightbox.setAttribute('id','lightbox');
objLightbox.style.display = 'none';
objLightbox.style.position = 'absolute';
objLightbox.style.zIndex = '100';
objBody.insertBefore(objLightbox, objOverlay.nextSibling);
// create link
var objLink = document.createElement("a");
objLink.setAttribute('href','#');
objLink.setAttribute('title','براي بستن کليک کنيد');
objLink.onclick = function () {hideLightbox(); return false;}
objLightbox.appendChild(objLink);
// preload and create close button image
var imgPreloadCloseButton = new Image();
// if close button image found,
imgPreloadCloseButton.onload=function(){
var objCloseButton = document.createElement("img");
objCloseButton.src = closeButton;
objCloseButton.setAttribute('id','closeButton');
objCloseButton.style.position = 'absolute';
objCloseButton.style.zIndex = '200';
objLink.appendChild(objCloseButton);
return false;
}
imgPreloadCloseButton.src = closeButton;
// create image
var objImage = document.createElement("img");
objImage.setAttribute('id','lightboxImage');
objLink.appendChild(objImage);
// create details div, a container for the caption and keyboard message
var objLightboxDetails = document.createElement("div");
objLightboxDetails.setAttribute('id','lightboxDetails');
objLightbox.appendChild(objLightboxDetails);
// create caption
var objCaption = document.createElement("div");
objCaption.setAttribute('id','lightboxCaption');
objCaption.style.display = 'none';
objLightboxDetails.appendChild(objCaption);
// create keyboard message
var objKeyboardMsg = document.createElement("div");
objKeyboardMsg.setAttribute('id','keyboardMsg');
objKeyboardMsg.innerHTML = 'براي بستن کليد <kbd>x</kbd> را فشار دهيد';
objLightboxDetails.appendChild(objKeyboardMsg);
}
//
// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function'){
window.onload = func;
} else {
window.onload = function(){
oldonload();
func();
}
}
}
addLoadEvent(initLightbox); // run initLightbox onLoad
and i have css for this js that it is not importat but i write it here:
#lightbox {
background-color: #eee;
padding: 10px;
border-bottom: 2px solid #666;
border-right: 2px solid #666;
}
#lightboxDetails {
font-size: 0.8em;
padding-top: 0.4em;
}
#lightboxCaption {
float: left;
}
#keyboardMsg {
float: right;
}
#closeButton {
top: 5px;
right: 5px;
}
#lightbox img {
border: none;
clear: both;
}
#overlay img {
border: none;
}
#overlay {
background: url(../LightBox/overlay.png);
}
* html #overlay {
background-color: #000;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src="../LightBox/overlay.png", sizingMethod="scale");
filter: alpha(opacity=70);
opacity: 0.7;
}
i think this code just run one time on window.load() and after i reload part of page it can't load again and don't work.
how i can resolve this problem?
tnks for reading my question...
Because to new html elements added after you need to recall all functions that work with it, for example recall functions that is called on document is created
When you get result from ajax and put it on html page, after write initLightbox();
You need to add initLightbox() here and change them with second php file. for first run my javascript
But you not write that code and I can't help you.
I can say only, put initlightbox after code where you receive response with ajax after lines where you insert new html elements.

Popover overlay in OpenLayers 3 does not extend beyond view

In the OpenLayers overlay example:
http://openlayers.org/en/v3.11.2/examples/overlay.html
If you click near the top of map most of the overlay is hidden. Is there a CSS trick, or an OpenLayers setting (I do not want to use the autoPan, which doesn't seem to work for popovers anyway), that will enable the entire popover to be shown even if it extends beyond the map view?
Here's a screenshot that illustrates the problem.
autoPan does work for popups, see here: http://openlayers.org/en/v3.11.2/examples/popup.html
However, I also had some trouble with autoPan so I didi it like this (Fiddle demo):
// move map if popop sticks out of map area:
var extent = map.getView().calculateExtent(map.getSize());
var center = map.getView().getCenter();
var pixelPosition = map.getPixelFromCoordinate([ coordinate[0], coordinate[1] ]);
var mapWidth = $("#map").width();
var mapHeight = $("#map").height();
var popoverHeight = $("#popup").height();
var popoverWidth = $("#popup").width();
var thresholdTop = popoverHeight+50;
var thresholdBottom = mapHeight;
var thresholdLeft = popoverWidth/2-80;
var thresholdRight = mapWidth-popoverWidth/2-130;
if(pixelPosition[0] < thresholdLeft || pixelPosition[0] > thresholdRight || pixelPosition[1]<thresholdTop || pixelPosition[1]>thresholdBottom) {
if(pixelPosition[0] < thresholdLeft) {
var newX = pixelPosition[0]+(thresholdLeft-pixelPosition[0]);
} else if(pixelPosition[0] > thresholdRight) {
var newX = pixelPosition[0]-(pixelPosition[0]-thresholdRight);
} else {
var newX = pixelPosition[0];
}
if(pixelPosition[1]<thresholdTop) {
var newY = pixelPosition[1]+(thresholdTop-pixelPosition[1]);
} else if(pixelPosition[1]>thresholdBottom) {
var newY = pixelPosition[1]-(pixelPosition[1]-thresholdBottom);
} else {
var newY = pixelPosition[1];
}
newCoordinate = map.getCoordinateFromPixel([newX, newY]);
newCenter = [(center[0]-(newCoordinate[0]-coordinate[0])), (center[1]-(newCoordinate[1]-coordinate[1])) ]
map.getView().setCenter(newCenter);
}
I added this code to the Popover Official Example in this fiddle demo:
// get DOM element generated by Bootstrap
var bs_element = document.getElementById(element.getAttribute('aria-describedby'));
var offset_height = 10;
// get computed popup height and add some offset
var popup_height = bs_element.offsetHeight + offset_height;
var clicked_pixel = evt.pixel;
// how much space (height) left between clicked pixel and top
var height_left = clicked_pixel[1] - popup_height;
var view = map.getView();
// get the actual center
var center = view.getCenter();
if (height_left < 0) {
var center_px = map.getPixelFromCoordinate(center);
var new_center_px = [
center_px[0],
center_px[1] + height_left
];
map.beforeRender(ol.animation.pan({
source: center,
start: Date.now(),
duration: 300
}));
view.setCenter(map.getCoordinateFromPixel(new_center_px));
}
To make the popup always appear inside the map view, I reversed the ol3 autopan function
So that it the popup is offset from the feature towards the view, instead of panning the view.
I am not sure why so many ol3 fiddles are not loading the map anymore.
http://jsfiddle.net/bunjil/L6rztwj8/48/
var getOverlayOffsets = function(mapInstance, overlay) {
const overlayRect = overlay.getElement().getBoundingClientRect();
const mapRect = mapInstance.getTargetElement().getBoundingClientRect();
const margin = 15;
// if (!ol.extent.containsExtent(mapRect, overlayRect)) //could use, but need to convert rect to extent
const offsetLeft = overlayRect.left - mapRect.left;
const offsetRight = mapRect.right - overlayRect.right;
const offsetTop = overlayRect.top - mapRect.top;
const offsetBottom = mapRect.bottom - overlayRect.bottom;
console.log('offsets', offsetLeft, offsetRight, offsetTop, offsetBottom);
const delta = [0, 0];
if (offsetLeft < 0) {
// move overlay to the right
delta[0] = margin - offsetLeft;
} else if (offsetRight < 0) {
// move overlay to the left
delta[0] = -(Math.abs(offsetRight) + margin);
}
if (offsetTop < 0) {
// will change the positioning instead of the offset to move overlay down.
delta[1] = margin - offsetTop;
} else if (offsetBottom < 0) {
// move overlay up - never happens if bottome-center is default.
delta[1] = -(Math.abs(offsetBottom) + margin);
}
return (delta);
};
/**
* Add a click handler to the map to render the popup.
*/
map.on('click', function(evt) {
var coordinate = evt.coordinate;
var hdms = ol.coordinate.toStringHDMS(ol.proj.transform(
coordinate, 'EPSG:3857', 'EPSG:4326'));
content.innerHTML = '<p>You clicked here:</p><code>' + hdms +
'</code>';
//overlay.setPosition(coordinate);
overlay.setOffset([0, 0]); // restore default
overlay.setPositioning('bottom-right'); // restore default
//overlay.set('autopan', true, false); //only need to do once.
overlay.setPosition(coordinate);
const delta = getOverlayOffsets(map, overlay);
if (delta[1] > 0) {
overlay.setPositioning('bottom-center');
}
overlay.setOffset(delta);
})
In this fiddle, the setPositioning() isn't working, so when you click near the top, the popup is under your mouse - it would be better to setPositioning('bottom-center');
automove would be a good feature to complement autopan.
In case of popover where "autoPan" option is not available you have to check extent's limits (top/bottom/right - left is skipped since popover is spawned on the center right of feature). So extending previous answer of Jonatas Walker a bit:
var bs_element = $('.popover');
var popup_height = bs_element.height();
var popup_width = bs_element.width();
var clicked_pixel = evt.pixel;
var view = map.getView();
var center = view.getCenter();
var height_left = clicked_pixel[1] - popup_height / 2; // from top
var height_left2 = clicked_pixel[1] + popup_height / 2; // from bottom
var width_left = clicked_pixel[0] + popup_width; // from right
var center_px = map.getPixelFromCoordinate(center);
var new_center_px = center_px;
var needs_recenter = false;
if (height_left2 > $("#map").height()) {
new_center_px[1] = height_left2 - center_px[1] + 30;
needs_recenter = true;
}
else if (height_left < 0) {
new_center_px[1] = center_px[1] + height_left;
needs_recenter = true;
}
if (width_left > $("#map").width()) {
new_center_px[0] = width_left - center_px[0] + 30;
needs_recenter = true;
}
if (needs_recenter)
view.setCenter(map.getCoordinateFromPixel(new_center_px));

Categories