Magnific Popup with upload image preview - image

I'm using Magnific popup to display an upload form where the user can select multiple images to upload and preview them before submitting the form, I let the user preview the images plus add a from inputs underneath the image when he clicks on it to enter the caption and alt for it, here's the code that I have ...
(function() {
if ($("a.uploadMediaImageForm").length) {
$("a.uploadMediaImageForm").magnificPopup({
type: 'inline',
preloader: false,
closeOnBgClick: false,
enableEscapeKey: false,
focus: '#name',
removalDelay: 500, //delay removal by X to allow out-animation
// When elemened is focused, some mobile browsers in some cases zoom in
// It looks not nice, so we disable it:
callbacks: {
beforeOpen: function() {
if ($(window).width() < 700) {
this.st.focus = false;
} else {
this.st.focus = '#name';
}
this.st.mainClass = this.st.el.attr('data-effect');
},
open: function() {
if ($("input#imageUpload").length) {
$("input#imageUpload").on('change', function() {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extension = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var previewHolder = $("ul.imagePreview");
previewHolder.empty();
if (extension == "gif" || extension == "png" || extension == "jpg" || extension == "jpeg") {
if (typeof(FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++) {
var reader = new FileReader();
reader.onload = function(e) {
$("<li><img src='" + e.target.result +"'></li>").appendTo(previewHolder);
}
previewHolder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Please select only images");
}
});
} //Image upload preview
if($("ul.imagePreview").length) {
$("ul.imagePreview").on("click", "li", function(event) {
if($(this).hasClass("selected")) {
$(this).removeClass("selected");
$(this).find("div").remove();
} else {
$(this).addClass("selected");
$(this).append("<div><label><span>Image Alt</span><input type='text'></label><label><span>Image Caption</span><input type='text'></label></div>");
}
});
$("ul.imagePreview").on("click", "div", function(event) {
event.stopPropagation();
});
}//add form when clicked on an image
},
beforeClose: function() {
// $("ul.imagePreview").empty();
var countFiles = "";
var imgPath = "";
var extension = "";
var previewHolder = $("ul.imagePreview");
previewHolder.empty();
}
},
midClick: true // allow opening popup on middle mouse click. Always set
});
}
})(); //popup Forms and Uploads
div.uploadPopup {
width: 80%;
margin: auto;
background: white;
position: relative;
padding: 40px;
}
label {
width: 100%;
margin-bottom: 20px;
clear: both;
}
ul.imagePreview {
width: 100%;
clear: both;
display: block;
}
ul.imagePreview li {
width: 100%;
display: block;
margin-bottom: 20px;
max-height: 150px;
cursor: pointer;
}
ul.imagePreview li.selected {
max-height: auto;
}
ul.imagePreview li img {
max-height: 150px;
display: block;
margin: auto;
}
<link href="https://cdn.jsdelivr.net/jquery.magnific-popup/1.0.0/magnific-popup.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.0.1/jquery.magnific-popup.min.js"></script>
Upload Media
<div id="uploadMediaImageForm" class="uploadPopup mfp-with-anim mfp-hide">
<form action="#">
<label class="upload">
<span>Upload Images</span>
<input id="imageUpload" type="file" multiple>
</label>
<ul class="imagePreview">
</ul>
</form>
</div>
Now everything works fine the first time, but when I close the popup and re-open it again, something wrong happens in the image previewer, it duplicates the images I choose and sometimes doesn't even show the image if it were the last image I choose before closing.
I tried to set all the variables before closing the popup and clear the image preview ul element, but that didn't help.
I need your help guys, what am I doing wrong here?
EDIT
I gave the form itself an id of "fileForm" and tried to reset the whole form and empty the ul.imagePreview before closing the popup with this code ...
$("#fileForm")[0].reset();
$("ul.imagePreview").empty();
But still no luck, it still duplicated any image I upload the second time after closing the popup and opening it again !!
need help here.

You are binding more and more listeners to the same event:
Your form always exists in your document even when the popup is closed, you just hide it most of the time (using the class mfp-hide).
Each time you open the popup, the callback "open" is called, which bind a function to the change event of your input, and this callback do the preview stuff.
But if you open the popup twice, it will bind again the same function to the same event on the same input. That's why you have duplicate: the code is called twice.
Move all your binding outside your callback so that they will be done once:
(function() {
if ($("input#imageUpload").length) {
$("input#imageUpload").on('change', function() {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extension = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var previewHolder = $("ul.imagePreview");
previewHolder.empty();
if (extension == "gif" || extension == "png" || extension == "jpg" || extension == "jpeg") {
if (typeof(FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++) {
var reader = new FileReader();
reader.onload = function(e) {
$("<li><img src='" + e.target.result +"'></li>").appendTo(previewHolder);
}
previewHolder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Please select only images");
}
});
} //Image upload preview
if($("ul.imagePreview").length) {
$("ul.imagePreview").on("click", "li", function(event) {
if($(this).hasClass("selected")) {
$(this).removeClass("selected");
$(this).find("div").remove();
} else {
$(this).addClass("selected");
$(this).append("<div><label><span>Image Alt</span><input type='text'></label><label><span>Image Caption</span><input type='text'></label></div>");
}
});
$("ul.imagePreview").on("click", "div", function(event) {
event.stopPropagation();
});
}//add form when clicked on an image
if ($("a.uploadMediaImageForm").length) {
$("a.uploadMediaImageForm").magnificPopup({
type: 'inline',
preloader: false,
closeOnBgClick: false,
enableEscapeKey: false,
focus: '#name',
removalDelay: 500, //delay removal by X to allow out-animation
// When elemened is focused, some mobile browsers in some cases zoom in
// It looks not nice, so we disable it:
callbacks: {
beforeOpen: function() {
if ($(window).width() < 700) {
this.st.focus = false;
} else {
this.st.focus = '#name';
}
this.st.mainClass = this.st.el.attr('data-effect');
},
beforeClose: function() {
///$("ul.imagePreview").empty();
var countFiles = "";
var imgPath = "";
var extension = "";
var previewHolder = $("ul.imagePreview");
previewHolder.empty();
$("#fileForm")[0].reset();
}
},
midClick: true // allow opening popup on middle mouse click. Always set
});
}
})(); //popup Forms and Uploads
div.uploadPopup {
width: 80%;
margin: auto;
background: white;
position: relative;
padding: 40px;
}
label {
width: 100%;
margin-bottom: 20px;
clear: both;
}
ul.imagePreview {
width: 100%;
clear: both;
display: block;
}
ul.imagePreview li {
width: 100%;
display: block;
margin-bottom: 20px;
max-height: 150px;
cursor: pointer;
}
ul.imagePreview li.selected {
max-height: auto;
}
ul.imagePreview li img {
max-height: 150px;
display: block;
margin: auto;
}
<link href="https://cdn.jsdelivr.net/jquery.magnific-popup/1.0.0/magnific-popup.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.0.1/jquery.magnific-popup.min.js"></script>
Upload Media
<div id="uploadMediaImageForm" class="uploadPopup mfp-with-anim mfp-hide">
<form action="#" id="fileForm">
<label class="upload">
<span>Upload Images</span>
<input id="imageUpload" type="file" multiple>
</label>
<ul class="imagePreview">
</ul>
</form>
</div>

Related

Autosave Status in CKEditor 5

I have gotten stuck on a rather simple aspect of the autosave feature and that is the current status of the action like found on the overview page: https://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/saving-data.html#demo. But it doesn't look like they actually reference it anywhere (example below).
My html is just:
<textarea class="form-control" name="notes" id="notes">{!! $shipmentShortage->notes !!}</textarea>
My create script is below, the autosave feature works just fine, but the status just isn't there:
<script>
ClassicEditor
.create( document.querySelector( '#notes' ), {
toolbar: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'undo', 'redo' ],
image: {
toolbar: [ 'imageStyle:full', 'imageStyle:side', '|', 'imageTextAlternative' ],
},
autosave: {
save( editor ) {
console.log(editor.getData());
// The saveData() function must return a promise
// which should be resolved when the data is successfully saved.
return saveData( editor.getData() );
}
}
} );
// Save the data to a fake HTTP server (emulated here with a setTimeout()).
function saveData( data ) {
return new Promise( resolve => {
setTimeout( () => {
console.log( 'Saved', data );
$.ajax({
url: '/osd/shortages/update',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
'shortage_id':'{{$shipmentShortage->id}}',
'notes': data,
},
dataType: 'json',
success: function (response) {
console.log('saved');
}
});
resolve();
}, 5000 );
} );
}
// Update the "Status: Saving..." info.
function displayStatus( editor ) {
const pendingActions = editor.plugins.get( 'PendingActions' );
const statusIndicator = document.querySelector( '#editor-status' );
pendingActions.on( 'change:hasAny', ( evt, propertyName, newValue ) => {
if ( newValue ) {
statusIndicator.classList.add( 'busy' );
} else {
statusIndicator.classList.remove( 'busy' );
}
} );
}
</script>
You are absolutely correct. They show us a sexy status updater but don't give us the code for it. Here is what I extracted from the demo page by looking at the page source. This should give you the Status updates as you asked. Let me know if you have any questions.
HTML:
<div id="snippet-autosave">
<textarea name="content" id="CKeditor_Notes">
Sample text
</textarea>
</div>
<!-- This will show the save status -->
<div id="snippet-autosave-header">
<div id="snippet-autosave-status" class="">
<div id="snippet-autosave-status_label">Status:</div>
<div id="snippet-autosave-status_spinner">
<span id="snippet-autosave-status_spinner-label"></span>
<span id="snippet-autosave-status_spinner-loader"></span>
</div>
</div>
</div>
CSS:
<style>
#snippet-autosave-header{
display: flex;
justify-content: space-between;
align-items: center;
background: var(--ck-color-toolbar-background);
border: 1px solid var(--ck-color-toolbar-border);
padding: 10px;
border-radius: var(--ck-border-radius);
/*margin-top: -1.5em;*/
margin-bottom: 1.5em;
border-top: 0;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
#snippet-autosave-status_spinner {
display: flex;
align-items: center;
position: relative;
}
#snippet-autosave-status_spinner-label {
position: relative;
}
#snippet-autosave-status_spinner-label::after {
content: 'Saved!';
color: green;
display: inline-block;
margin-right: var(--ck-spacing-medium);
}
/* During "Saving" display spinner and change content of label. */
#snippet-autosave-status.busy #snippet-autosave-status_spinner-label::after {
content: 'Saving...';
color: red;
}
#snippet-autosave-status.busy #snippet-autosave-status_spinner-loader {
display: block;
width: 16px;
height: 16px;
border-radius: 50%;
border-top: 3px solid hsl(0, 0%, 70%);
border-right: 2px solid transparent;
animation: autosave-status-spinner 1s linear infinite;
}
#snippet-autosave-status,
#snippet-autosave-server {
display: flex;
align-items: center;
}
#snippet-autosave-server_label,
#snippet-autosave-status_label {
font-weight: bold;
margin-right: var(--ck-spacing-medium);
}
#snippet-autosave + .ck.ck-editor .ck-editor__editable {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
#snippet-autosave-lag {
padding: 4px;
}
#snippet-autosave-console {
max-height: 300px;
overflow: auto;
white-space: normal;
background: #2b2c26;
transition: background-color 500ms;
}
#snippet-autosave-console.updated {
background: green;
}
#keyframes autosave-status-spinner {
to {
transform: rotate( 360deg );
}
}
</style>
The rest is just initializing the Editor just like on the demo page here.
ClassicEditor
.create(document.querySelector('#CKeditor_Notes'), {
autosave: {
save(editor) {
return saveData(editor.getData());
}
}
})
.then(editor => {
window.editor = editor;
displayStatus(editor);
})
.catch(err => {
console.error(err.stack);
});
// Save the data to Server Side DB.
function saveData(data) {
return new Promise(resolve => {
setTimeout(() => {
console.log('Saved', data);
SaveDataToDB(data)
resolve();
});
});
}
// Update the "Status: Saving..." info.
function displayStatus(editor) {
const pendingActions = editor.plugins.get('PendingActions');
const statusIndicator = document.querySelector('#snippet-autosave-status');
pendingActions.on('change:hasAny', (evt, propertyName, newValue) => {
if (newValue) {
statusIndicator.classList.add('busy');
} else {
statusIndicator.classList.remove('busy');
}
});
}

How can i stop the reloading of a .txt file with AJAX after loading it with setInterval?

I am building a chatsystem and i am using the AJAX technique for the asynchronous loading of a flat .txt file.
Next to the AJAX technique above, i also have a button that lets you manually start and stop the reloading of the flat .txt file.
When you start the reloading, it will do this every second/1000ms.
So far so good.. the problem comes when i want to clear the setInterval function with the clearInterval function. It works only once, and after i have restarted the loading of the document again through the start button, i can't stop it from reloading again with the other stop button.
I have tried almost every solution on stackoverflow regarding setInterval and clearInterval, but none of them seem to provide a solution or some of the threads are just left open without a solution. Is it even possible to stop and restart? and then stop again etc..
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("chatlog").innerHTML = this.responseText;
}
};
xhttp.open("POST", "chatlog.txt", true);
xhttp.send();
}
function scrollWin(x,y) {
window.scrollBy(x,y);
}
var reload = setInterval(loadDoc,1000);
var myStartFunction = function () {
var begin = setInterval(loadDoc,1000);
}
var myStopFunction = function() {
var stop = clearInterval(reload);
}
var elmnt = document.getElementById("chatlog");
function scrollToTop() {
elmnt.scrollIntoView(true); // Top
}
function scrollToBottom() {
elmnt.scrollIntoView(false); // Bottom
}
var autoScroll = setInterval(function () {scrollToBottom()},3000);
function stopAutoScroll() {
clearInterval(autoScroll);
}
BODY
{
margin: 0;
}
.container-one
{
width: 25%;
}
.buttons
{
position: fixed;
border-right: 1px solid #000000;
height: 100%;
z-index: 1;
top: 0px;
background-color: #7F7F7F;
}
.buttons UL
{
list-style-type: none;
margin: 0;
padding: 0;
}
.buttons LI BUTTON
{
width: 100%;
display: block;
border: 1px solid #020202;
padding: 10px;
}
.firstbox
{
margin-left: 240px;
overflow: auto;
margin-top: 115px;
/*[disabled]border:1px solid #000000;*/
}
.chatheader H1
{
text-align: center;
padding: 20px;
margin: 0 auto 0 9%;
border-bottom: 5px solid #000000;
position: fixed;
background-color: #7C7C7C;
top: 0px;
width: 100%;
}
.firstbox P
{
margin-left: auto;
margin-right: auto;
/*[disabled]border:0px solid #000000;*/
/*border-radius: 20px*/
padding: 10%;
background-color: #E0E0E0;
width: 50%;
/*[disabled]height:300px;*/
/*[disabled]overflow:scroll;*/
text-align: center;
}
#chatlog
{
height: auto;
}
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="chatstyle-reload.css">
<meta charset="utf-8" />
<!--<meta http-equiv="refresh" content="5" > -->
<title>Test page for requesting a webpage with the AJAX technique!</title>
</head>
<body>
<div class="container-one">
<div class="buttons">
<ul>
<li><button type="button" onclick="loadDoc()">Request the chatlog</button></li>
<li><button type="button" id="reloadBtn" onclick="myStartFunction()">Start updating the chatlog</button></li>
<li><button type="button" id="stopBtn" onclick="myStopFunction()">Stop reloading the chatlog</button></li>
<li><button type="button" onclick="document.getElementById('chatlog').innerHTML = 'Chatlog is hidden'">Hide chatlog</button></li>
<li><button type="button" onclick="scrollWin(0,-50)">Go to top of page</button></li>
<li><button type="button" onclick="scrollWin(0,200)">Go to bottom of page</button></li>
<li><button type="button" onclick="scrollToTop()">Scroll to the top of the element</button></li>
<li><button type="button" onclick="scrollToBottom()">Scroll to the bottom of the element</button></li>
<li><button type="button" onclick="stopAutoScroll()">Stop autoscroll</button></li>
<li><button type="button"> Go back => to checkandtest.nl</button></li>
</ul>
</div>
</div>
<div class="chatheader">
<h1>Display the current chatlog in real-time</h1>
</div>
<div class="firstbox">
<p id="chatlog"></p>
</div>
<script src="functions.js"> </script>
</body>
</html>
Your problem is here:
var reload = setInterval(loadDoc,1000);
var myStartFunction = function () {
var begin = setInterval(loadDoc,1000);
}
var myStopFunction = function() {
var stop = clearInterval(reload);
}
You create an interal via setInterval and store it into reload, which can be correctly stopped, but when you start again via myStartFunction, you store it into a local unused variable called begin and at stop you intend to stop the interval having the id of reload, which was already stopped. Instead you will need to change myStartFunction as such:
var myStartFunction = function () {
myStopFunction(); //Stop any previous unstopped interval
reload = setInterval(loadDoc,1000);
}
EDIT
Here I elaborate the problem we had before the last edit on this answer. Before the last edit we had var reload = setInterval(loadDoc,1000); inside the myStartFunction, which creates a local variable called reload, but this local variable "shadows" the outer variable called reload, so, we were setting the value of the local variable and we expected the value to be assigned to the global variable. It was a typo on my part, but it's good to explain it. Let me give you an example:
var myVariable = 1;
function foo() {
var myVariable = 2;
}
foo();
console.log(myVariable); //1
As you can see, we have two variables called myVariable. In the scope of the function we created a variable with the same name and assign a value of 2. Even though we call the function, the outer variable doesn't budge. Now, let's remove the var keyword inside the function:
var myVariable = 1;
function foo() {
myVariable = 2;
}
foo();
console.log(myVariable); //2

Google Place API: how to autocomplete API for custom search?

I am new to Google Api....Can Anyone please provide me code for PLACE Autocomplete if I only want to have autocomplete search-results related to hospitals only such that in search bar,it should display only hospitals name and nothing else.
Here Is My Code.It's Just Showing City Names in Search Field. I want Hospital's Name To be Searched.
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete Hotel Search</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
table {
font-size: 12px;
}
#map {
width: 440px;
}
#listing {
position: absolute;
width: 200px;
height: 470px;
overflow: auto;
left: 442px;
top: 0px;
cursor: pointer;
overflow-x: hidden;
}
#findhotels {
position: absolute;
text-align: right;
width: 100px;
font-size: 14px;
padding: 4px;
z-index: 5;
background-color: #fff;
}
#locationField {
position: absolute;
width: 190px;
height: 25px;
left: 108px;
top: 0px;
z-index: 5;
background-color: #fff;
}
#controls {
position: absolute;
left: 300px;
width: 140px;
top: 0px;
z-index: 5;
background-color: #fff;
}
#autocomplete {
width: 100%;
}
#country {
width: 100%;
}
.placeIcon {
width: 20px;
height: 34px;
margin: 4px;
}
.hotelIcon {
width: 24px;
height: 24px;
}
#resultsTable {
border-collapse: collapse;
width: 240px;
}
#rating {
font-size: 13px;
font-family: Arial Unicode MS;
}
.iw_table_row {
height: 18px;
}
.iw_attribute_name {
font-weight: bold;
text-align: right;
}
.iw_table_icon {
text-align: right;
}
</style>
</head>
<body>
<div id="findhotels">
Find hotels in:
</div>
<div id="locationField">
<input id="autocomplete" placeholder="Enter a city" type="text" />
</div>
<div id="controls">
<select id="country">
<option value="all">All</option>
<option value="au">Australia</option>
<option value="br">Brazil</option>
<option value="ca">Canada</option>
<option value="fr">France</option>
<option value="de">Germany</option>
<option value="mx">Mexico</option>
<option value="nz">New Zealand</option>
<option value="it">Italy</option>
<option value="za">South Africa</option>
<option value="es">Spain</option>
<option value="pt">Portugal</option>
<option value="us" selected>U.S.A.</option>
<option value="uk">United Kingdom</option>
</select>
</div>
<div id="map"></div>
<div id="listing">
<table id="resultsTable">
<tbody id="results"></tbody>
</table>
</div>
<div style="display: none">
<div id="info-content">
<table>
<tr id="iw-url-row" class="iw_table_row">
<td id="iw-icon" class="iw_table_icon"></td>
<td id="iw-url"></td>
</tr>
<tr id="iw-address-row" class="iw_table_row">
<td class="iw_attribute_name">Address:</td>
<td id="iw-address"></td>
</tr>
<tr id="iw-phone-row" class="iw_table_row">
<td class="iw_attribute_name">Telephone:</td>
<td id="iw-phone"></td>
</tr>
<tr id="iw-rating-row" class="iw_table_row">
<td class="iw_attribute_name">Rating:</td>
<td id="iw-rating"></td>
</tr>
<tr id="iw-website-row" class="iw_table_row">
<td class="iw_attribute_name">Website:</td>
<td id="iw-website"></td>
</tr>
</table>
</div>
</div>
<script>
// This example uses the autocomplete feature of the Google Places API.
// It allows the user to find all hotels in a given place, within a given
// country. It then displays markers for all the hotels returned,
// with on-click details for each hotel.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map, places, infoWindow;
var markers = [];
var autocomplete;
var countryRestrict = {'country': 'us'};
var MARKER_PATH = 'https://developers.google.com/maps/documentation/javascript/images/marker_green';
var hostnameRegexp = new RegExp('^https?://.+?/');
var countries = {
'au': {
center: {lat: -25.3, lng: 133.8},
zoom: 4
},
'br': {
center: {lat: -14.2, lng: -51.9},
zoom: 3
},
'ca': {
center: {lat: 62, lng: -110.0},
zoom: 3
},
'fr': {
center: {lat: 46.2, lng: 2.2},
zoom: 5
},
'de': {
center: {lat: 51.2, lng: 10.4},
zoom: 5
},
'mx': {
center: {lat: 23.6, lng: -102.5},
zoom: 4
},
'nz': {
center: {lat: -40.9, lng: 174.9},
zoom: 5
},
'it': {
center: {lat: 41.9, lng: 12.6},
zoom: 5
},
'za': {
center: {lat: -30.6, lng: 22.9},
zoom: 5
},
'es': {
center: {lat: 40.5, lng: -3.7},
zoom: 5
},
'pt': {
center: {lat: 39.4, lng: -8.2},
zoom: 6
},
'us': {
center: {lat: 37.1, lng: -95.7},
zoom: 3
},
'uk': {
center: {lat: 54.8, lng: -4.6},
zoom: 5
}
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: countries['us'].zoom,
center: countries['us'].center,
mapTypeControl: false,
panControl: false,
zoomControl: false,
streetViewControl: false
});
infoWindow = new google.maps.InfoWindow({
content: document.getElementById('info-content')
});
// Create the autocomplete object and associate it with the UI input control.
// Restrict the search to the default country, and to place type "cities".
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */ (
document.getElementById('autocomplete')), {
types: ['(cities)'],
componentRestrictions: countryRestrict
});
places = new google.maps.places.PlacesService(map);
autocomplete.addListener('place_changed', onPlaceChanged);
// Add a DOM event listener to react when the user selects a country.
document.getElementById('country').addEventListener(
'change', setAutocompleteCountry);
}
// When the user selects a city, get the place details for the city and
// zoom the map in on the city.
function onPlaceChanged() {
var place = autocomplete.getPlace();
if (place.geometry) {
map.panTo(place.geometry.location);
map.setZoom(15);
search();
} else {
document.getElementById('autocomplete').placeholder = 'Enter a city';
}
}
// Search for hotels in the selected city, within the viewport of the map.
function search() {
var search = {
bounds: map.getBounds(),
types: ['lodging']
};
places.nearbySearch(search, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
clearResults();
clearMarkers();
// Create a marker for each hotel found, and
// assign a letter of the alphabetic to each marker icon.
for (var i = 0; i < results.length; i++) {
var markerLetter = String.fromCharCode('A'.charCodeAt(0) + (i % 26));
var markerIcon = MARKER_PATH + markerLetter + '.png';
// Use marker animation to drop the icons incrementally on the map.
markers[i] = new google.maps.Marker({
position: results[i].geometry.location,
animation: google.maps.Animation.DROP,
icon: markerIcon
});
// If the user clicks a hotel marker, show the details of that hotel
// in an info window.
markers[i].placeResult = results[i];
google.maps.event.addListener(markers[i], 'click', showInfoWindow);
setTimeout(dropMarker(i), i * 100);
addResult(results[i], i);
}
}
});
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
if (markers[i]) {
markers[i].setMap(null);
}
}
markers = [];
}
// Set the country restriction based on user input.
// Also center and zoom the map on the given country.
function setAutocompleteCountry() {
var country = document.getElementById('country').value;
if (country == 'all') {
autocomplete.setComponentRestrictions({'country': []});
map.setCenter({lat: 15, lng: 0});
map.setZoom(2);
} else {
autocomplete.setComponentRestrictions({'country': country});
map.setCenter(countries[country].center);
map.setZoom(countries[country].zoom);
}
clearResults();
clearMarkers();
}
function dropMarker(i) {
return function() {
markers[i].setMap(map);
};
}
function addResult(result, i) {
var results = document.getElementById('results');
var markerLetter = String.fromCharCode('A'.charCodeAt(0) + (i % 26));
var markerIcon = MARKER_PATH + markerLetter + '.png';
var tr = document.createElement('tr');
tr.style.backgroundColor = (i % 2 === 0 ? '#F0F0F0' : '#FFFFFF');
tr.onclick = function() {
google.maps.event.trigger(markers[i], 'click');
};
var iconTd = document.createElement('td');
var nameTd = document.createElement('td');
var icon = document.createElement('img');
icon.src = markerIcon;
icon.setAttribute('class', 'placeIcon');
icon.setAttribute('className', 'placeIcon');
var name = document.createTextNode(result.name);
iconTd.appendChild(icon);
nameTd.appendChild(name);
tr.appendChild(iconTd);
tr.appendChild(nameTd);
results.appendChild(tr);
}
function clearResults() {
var results = document.getElementById('results');
while (results.childNodes[0]) {
results.removeChild(results.childNodes[0]);
}
}
// Get the place details for a hotel. Show the information in an info window,
// anchored on the marker for the hotel that the user selected.
function showInfoWindow() {
var marker = this;
places.getDetails({placeId: marker.placeResult.place_id},
function(place, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
infoWindow.open(map, marker);
buildIWContent(place);
});
}
// Load the place information into the HTML elements used by the info window.
function buildIWContent(place) {
document.getElementById('iw-icon').innerHTML = '<img class="hotelIcon" ' +
'src="' + place.icon + '"/>';
document.getElementById('iw-url').innerHTML = '<b><a href="' + place.url +
'">' + place.name + '</a></b>';
document.getElementById('iw-address').textContent = place.vicinity;
if (place.formatted_phone_number) {
document.getElementById('iw-phone-row').style.display = '';
document.getElementById('iw-phone').textContent =
place.formatted_phone_number;
} else {
document.getElementById('iw-phone-row').style.display = 'none';
}
// Assign a five-star rating to the hotel, using a black star ('✭')
// to indicate the rating the hotel has earned, and a white star ('✩')
// for the rating points not achieved.
if (place.rating) {
var ratingHtml = '';
for (var i = 0; i < 5; i++) {
if (place.rating < (i + 0.5)) {
ratingHtml += '✩';
} else {
ratingHtml += '✭';
}
document.getElementById('iw-rating-row').style.display = '';
document.getElementById('iw-rating').innerHTML = ratingHtml;
}
} else {
document.getElementById('iw-rating-row').style.display = 'none';
}
// The regexp isolates the first part of the URL (domain plus subdomain)
// to give a short URL for displaying in the info window.
if (place.website) {
var fullUrl = place.website;
var website = hostnameRegexp.exec(place.website);
if (website === null) {
website = 'http://' + place.website + '/';
fullUrl = website;
}
document.getElementById('iw-website-row').style.display = '';
document.getElementById('iw-website').textContent = website;
} else {
document.getElementById('iw-website-row').style.display = 'none';
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=My_Api_Key&libraries=places&callback=initMap"
async defer></script>
</body>
</html>
To be very clear for rookies like me (because I wasted a lot of time on this) you cannot set an Autocomplete request to return specific types of places.
For example, if you want Autocomplete to return just hospitals, or just restaurants, or just parks, as of April 2022, you can't.
This issue requesting that ability was opened in 2011 and hasn't been handled yet. https://issuetracker.google.com/issues/35820774
You can only set Autocomplete to return classes of places, by setting the type to something in Table 3 here - https://developers.google.com/maps/documentation/places/web-service/supported_types
Table 3 options are:
geocode
address
establishment
regions
cities
in the Search Function, in variable search change types field to hospital like:
var search = {
bounds: map.getBounds(),
types: ['hospital']
};
and in the Autocomplete predictions so far only "country" restriction is supported as stated in the documentation:
"componentRestrictions can be used to restrict results to specific groups. Currently, you can use componentRestrictions to filter by up to 5 countries. Countries must be passed as as a two-character, ISO 3166-1 Alpha-2 compatible country code. Multiple countries must be passed as a list of country codes."
https://developers.google.com/maps/documentation/javascript/places-autocomplete
If you would like to add this feature for Autocomplete, there is already a case in the issue tracker where you can add your vote to support this request in:
https://issuetracker.google.com/issues/35820774

Modal image with download link

I have a modal image that when clicked, will open full-screen with the text displayed from the alt tag in the image. I grabbed the code off another site so need to change it to add a download link within the modal so when the link is clicked it will download a file. Is this possible in the below code?
Code below:
<img id="myImg1" src="test.png" alt="Hello" width="95" height="146">
<!-- The Modal -->
<script
<div id="myModal1" class="modal">
<span class="close">x</span>
<img class="modal-content" id="img01">
<div id="caption">
<div id="caption1"></div>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal1');
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg1');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption1");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
Any assistance would be much appreciated.
[![<!DOCTYPE html>
<html>
<head>
<style>
#myImg {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}
#myImg:hover {opacity: 0.7;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}
/* Modal Content (image) */
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
/* Caption of Modal Image */
#caption {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #ccc;
padding: 10px 0;
height: 150px;
}
/* Add Animation */
.modal-content, #caption {
-webkit-animation-name: zoom;
-webkit-animation-duration: 0.6s;
animation-name: zoom;
animation-duration: 0.6s;
}
#-webkit-keyframes zoom {
from {-webkit-transform:scale(0)}
to {-webkit-transform:scale(1)}
}
#keyframes zoom {
from {transform:scale(0)}
to {transform:scale(1)}
}
/* The Close Button */
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
/* 100% Image Width on Smaller Screens */
#media only screen and (max-width: 700px){
.modal-content {
width: 100%;
}
}
</style>
</head>
<body>
<h2>Image Modal</h2>
<p>In this example, we use CSS to create a modal (dialog box) that is hidden by default.</p>
<p>We use JavaScript to trigger the modal and to display the current image inside the modal when it is clicked on. Also note that we use the value from the image's "alt" attribute as an image caption text inside the modal.</p>
<img id="myImg" src="img_fjords.jpg" alt="Trolltunga, Norway" width="300" height="200">
<!-- The Modal -->
<div id="myModal" class="modal">
Download
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")\[0\];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
</script>
</body>
</html>

Customizing scrollable plugin with prevpage and nextpage over the image? (see mock up)

I am implementing a scrollable for a portfolio gallery.
(scrollable = scrollable plugin from http://flowplayer.org/tools/index.html )
There will be one item visible at a time.
By default, scrollable positions the prev/next buttons outside of the image area and clicking on the current image advances the scrollable content.
I would like to have the prev/next render within the image area.
I would like to have an image caption appear when mousing over the lower part of the image.
Mock-up:
http://i303.photobucket.com/albums/nn160/upstagephoto/mockups/scrollable_mockup.jpg
Any ideas on how to achieve one or both of these?
Thank you!
The main part of your approach will be like this in your html:
<div id="mainContainer">
<div class="scrollable">
<div class="items">
<div class="scrollableEl">
<img src="yourimage.jpg" />
<div class="caption">Your caption</div>
</div>
<div class="scrollableEl">
<img src="yourimage2.jpg" />
<div class="caption">Your caption 2</div>
</div>
... so on ...
</div>
</div>
«
«
</div>
And like so in your CSS:
.scrollable {
position:relative;
overflow:hidden;
width: 660px;
height:90px;
}
.scrollable .items {
width:20000em;
position:absolute;
}
.items .scrollableEl {
float:left;
positon: relative;
}
.items .scrollableEl .caption {
display:none;
position: absolute;
bottom: 0;
height: 100px;
width: 660px;
}
.items .scrollableEl:hover .caption { /*this will show your caption on mouse over */
display:none;
}
.next, .prev {
position: absolute;
top: 0;
display: block;
width: 30px;
height: 100%;
}
.next {
right: 0;
}
.prev {
left: 0;
}
#mainContainer {
position: relative;
}
The javascript should be fairly standard. Hope this helps!
DEMO: http://jsbin.com/ijede/2 SOURCE: http://jsbin.com/ijede/2/edit
$(function() {
// 5 minute slide show ;-)
$('.next,.prev').click(function(e) {
e.preventDefault();
var pos = parseInt($('.current').attr('id').split('_')[1]);
var tot = $('.slides a').size() - 1;
var click = this.className;
var new_pos = (click == 'next') ? pos + 1: pos - 1;
var slide = ( click == 'next') ?
(pos < tot ? true : false) : (pos > 0 ? true : false);
if (slide) $('.current').toggle(500,function() {
$(this).removeClass('current');
});
$('#pos_' + new_pos).toggle(500,function() {
$(this).attr('class', 'current');
});
});
//cross-browser div :hover
$('.next,.prev').hover(function() {
$(this).children().children().fadeIn(500);
},function() {
$(this).children().children().fadeOut(500);
});
//auto add unique id to each image
$('.slides a').each(function(e) {
$(this).attr('id', 'pos_' + e);
if (!e) $(this).attr('class', 'current');
});
});​
CSS on source!
NOTE: since read the plugin doc require more time for me than make a slideshow from scratch, i have maked a fresh one!
hope you like it!

Resources