Google Place API: how to autocomplete API for custom search? - google-api
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
Related
How to optimize display & interactive with large svg image without Lag in FabricJS
I have a fabricJS editor with some large svg files, therefore, when I interactive with ( move / drag ) items on the editor I fill it very lag & heavy. How to optimize using large svg files with fabricJS ? big_image_1.svg: 4.4MB big_image_2.svg: 6.1MB big_image_3.svg: 4.1MB big_image_4.svg: 13.6MB Here is my code: var canvas; var canvasObject = document.getElementById("editorCanvas"); // set canvas equal size with div $(canvasObject).width($("#canvasContainer").width()); $(canvasObject).height($("#canvasContainer").height()); canvas = new fabric.Canvas('editorCanvas', { backgroundColor: 'white', selectionLineWidth: 2, width: $("#canvasContainer").width(), height: $("#canvasContainer").height() }); for (var i = 0; i < 4; i++) { var bigImage = new fabric.Image(); bigImage.left = 10 * (i + 1); bigImage.top = 10 * (i + 1); bigImage["objectCaching"] = true; canvas.add(bigImage); bigImage.setSrc('https://futushigame.firebaseapp.com/big_image/big_image_' + (i + 1) + '.svg', function(imageObject) { imageObject.set('dirty', true); canvas.renderAll(); setObjectCoords(); }); } function setObjectCoords() { canvas.forEachObject(function(object) { object.setCoords(); }); } #canvasContainer { width: 100%; height: 100vh; background-color: gray; } <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.3/fabric.js"></script> <div id="canvasContainer"> <canvas id="editorCanvas"></canvas> </div> Drag items are filling heavy & lag
You can rewrite needsItsOwnCache from fabric.Image class. var canvasObject = document.getElementById("editorCanvas"); // set canvas equal size with div $(canvasObject).width($("#canvasContainer").width()); $(canvasObject).height($("#canvasContainer").height()); canvas = new fabric.Canvas('editorCanvas', { backgroundColor: 'white', selectionLineWidth: 2, width: $("#canvasContainer").width(), height: $("#canvasContainer").height() }); for (var i = 0; i < 4; i++) { var bigImage = new fabric.Image(); bigImage.left = 10 * (i + 1); bigImage.top = 10 * (i + 1); // bigImage["objectCaching"] = true; bigImage["ownCaching"] = true; // bigImage["clipPath"] = []; canvas.add(bigImage); bigImage.setSrc('https://futushigame.firebaseapp.com/big_image/big_image_' + (i + 1) + '.svg', function(imageObject) { //imageObject.set('dirty', true); canvas.renderAll(); setObjectCoords(); }); } function setObjectCoords() { canvas.forEachObject(function(object) { object.setCoords(); }); } fabric.Image.prototype.needsItsOwnCache = function() { return true } #canvasContainer { width: 100%; height: 100vh; background-color: gray; } <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.3/fabric.js"></script> <div id="canvasContainer"> <canvas id="editorCanvas"></canvas> </div>
Fix overlap on multiple stacked barchart
The fiddle below shows 2 stacked bar charts on the multichart, what styling can be applied to position them so they do not overlap? https://jsfiddle.net/ramgp76m/ var testdata = [[{'x':0,'y':0.18308100617846632},{'x':1,'y':0.18308100617846632},{'x':2,'y':0.18308100617846632},{'x':3,'y':0.18308100617846632},{'x':4,'y':0.18308100617846632},{'x':5,'y':0.18308100617846632},{'x':6,'y':0.18308100617846632},{'x':7,'y':0.18308100617846632},{'x':8,'y':0.18308100617846632},{'x':9,'y':0.18308100617846632},{'x':10,'y':0.18308100617846632},{'x':11,'y':0.18308100617846632},{'x':12,'y':0.18308100617846632},{'x':13,'y':0.18308100617846632}],[{'x':0,'y':0.3848121729491284},{'x':1,'y':0.3848121729491284},{'x':2,'y':0.6064571483967448},{'x':3,'y':0.3848121729491284},{'x':4,'y':0.3848121729491284},{'x':5,'y':0.3848121729491284},{'x':6,'y':0.3848121729491284},{'x':7,'y':0.3848121729491284},{'x':8,'y':0.3848121729491284},{'x':9,'y':0.3848121729491284},{'x':10,'y':0.3848121729491284},{'x':11,'y':0.3848121729491284},{'x':12,'y':0.3848121729491284},{'x':13,'y':0.3848121729491284}],[{'x':0,'y':0.1399518819223031},{'x':1,'y':0.1399518819223031},{'x':2,'y':0.1399518819223031},{'x':3,'y':0.1399518819223031},{'x':4,'y':0.1399518819223031},{'x':5,'y':0.1399518819223031},{'x':6,'y':0.1399518819223031},{'x':7,'y':0.1399518819223031},{'x':8,'y':0.1399518819223031},{'x':9,'y':0.1399518819223031},{'x':10,'y':0.1399518819223031},{'x':11,'y':0.1399518819223031},{'x':12,'y':0.1399518819223031},{'x':13,'y':0.1399518819223031}],[{'x':0,'y':0.661327785950392},{'x':1,'y':0.661327785950392},{'x':2,'y':0.661327785950392},{'x':3,'y':0.661327785950392},{'x':4,'y':0.661327785950392},{'x':5,'y':0.661327785950392},{'x':6,'y':0.661327785950392},{'x':7,'y':0.661327785950392},{'x':8,'y':0.661327785950392},{'x':9,'y':0.661327785950392},{'x':10,'y':0.661327785950392},{'x':11,'y':0.661327785950392},{'x':12,'y':0.661327785950392},{'x':13,'y':0.661327785950392}],[{'x':0,'y':0.12912787561339684},{'x':1,'y':0.19822891999644937},{'x':2,'y':0.19524003452978822},{'x':3,'y':0.2022421270610378},{'x':4,'y':2.9546625202733403},{'x':5,'y':0.17245495458323432},{'x':6,'y':0.17518206801386724},{'x':7,'y':0.19136958873352614},{'x':8,'y':0.20233322594961195},{'x':9,'y':0.791354544787474},{'x':10,'y':1.8421373975341035},{'x':11,'y':0.50545378694344},{'x':12,'y':0.15839045811626706},{'x':13,'y':0.17249910157699552}]].map(function(data, i) { return { key: 'Stream' + i, values: data }; }); testdata[1].type = "bar"; testdata[1].yAxis = 1; testdata[2].type = "bar"; testdata[2].yAxis = 1; testdata[3].type = "bar"; testdata[3].yAxis = 2; testdata[4].type = "bar"; testdata[4].yAxis = 2; nv.addGraph(function() { var chart = nv.models.multiChart() .margin({top: 30, right: 60, bottom: 50, left: 70}) .color(d3.scale.category10().range()); chart.xAxis.tickFormat(d3.format(',f')); chart.yAxis1.tickFormat(d3.format(',.1f')); chart.yAxis2.tickFormat(d3.format(',.1f')); chart.bars1.stacked(true); chart.bars2.stacked(true); chart.bars1.groupSpacing(0.5); chart.bars2.groupSpacing(0.5); d3.select('#chart1 svg') .datum(testdata) .transition().duration(500).call(chart); return chart; }); text { font: 12px sans-serif; } svg { display: block; } html, body, #chart1, svg { margin: 0px; padding: 0px; height: 100%; width: 100%; } <link href="https://nvd3-community.github.io/nvd3/build/nv.d3.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.2/d3.min.js"></script> <script src="https://nvd3-community.github.io/nvd3/build/nv.d3.js"></script> <div id="chart1" > <svg> </svg> </div>
Here's what I did different to your code. Changed nv.models.multiChart() to nv.models.multiBarChart() Updated chart to include : .showControls(false) .stacked(true); Replaced the chart properties to the following : chart.xAxis.tickFormat(d3.format(',f')); chart.yAxis.tickFormat(d3.format(',.1f')); //chart.xAxis.tickFormat(d3.format(',f')); //chart.yAxis.tickFormat(d3.format(',.1f')); //chart.yAxis2.tickFormat(d3.format(',.1f')); //chart.bars1.stacked(true); //chart.bars2.stacked(true); //chart.bars1.groupSpacing(0.5); //chart.bars2.groupSpacing(0.5); You can find a working version of your code here Hope it helps.
Parallax effect - calculate child offset to parent on scroll
I'm trying to create a parallax effect whereby an absolutely positioned child element should move at a rate slower than it's parent on scroll. The child will always be 130% height of the parent but the parent can be any height: HTML: <div class="parallax-window lg"> <div class="parallax-image image-1"></div> <div class="parallax-content">Hello World</div> </div> <div class="parallax-window"> <div class="parallax-image image-2"></div> <div class="parallax-content">Hello World</div> </div> CSS: .parallax-window { min-height: 300px; position: relative; overflow: hidden; } .parallax-window.lg { min-height: 600px; } .parallax-image { position: absolute; top: 0; left: 0; width: 100%; height: 130%; background-size: cover; background-repeat: no-repeat; background-position: 50% 50%; transform: translate3d(0, 0, 0); z-index: -1; } .image-1 { background-image: url(https://i.ytimg.com/vi/TbC-vUPMR7k/maxresdefault.jpg); } .image-2 { background-image: url(https://i.ytimg.com/vi/xi5-YrAEChc/maxresdefault.jpg); } I have a formula to move the image but my maths is clearly way off: var win = $(window), win_h = win.height(), parallaxers = $('.parallax-window'); function scroll_events() { var win_top = win.scrollTop(), win_btm = win_top + win_h; parallaxers.each(function() { var cont = $(this), cont_top = cont.offset().top, cont_h = cont.height(), cont_btm = cont_top + cont_h, para = cont.find('.parallax-image'), para_h = Math.round(cont_h * 1.3); if (cont_btm > win_top && cont_top <= win_btm) { var diff = (win_h - cont_h) / (win_h - para_h), value = -Math.round((win_top * diff)); // para.css('transform', 'translate3d(0,' + value*-1 + 'px, 0)'); para.css('top', value + 'px'); } }); } The images move but not at the correct rate. The image should be in line with the top of the parent when the element first comes into the viewport. Then after scrolling, the bottom of the image should be in line with the bottom of the parent when it reaches the top of the viewport. Any help would be massively appreciated! FIDDLE (https://jsfiddle.net/8dwLwgy7/1/)
I figured this out. For anyone stumbling on this in the future - the trick was to replace the window scrolled value with the remainder of the window scrolled amount minus the element's offset top, minus the height of the element. Then calculate the speed by dividing the difference between the container height and the element height with largest of either the window and the container: // Wrong: // value = -Math.round((win_top * diff)); // Right: var diff = elem_h - cont_h, max = Math.max(cont_h, win_h), speed = diff / max, cont_scrolled = win_top - cont_top - cont_h, value = Math.round(cont_scrolled * speed); para.css('top', value + 'px'); Full working code: (function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }()); (function($) { var win = $(window), win_h = win.height(); parallaxers = $('.parallax-window'), parallax_objs = [], scroll_busy = false; function init_parallax() { win_h = win.height(); parallax_objs = []; parallaxers.each(function() { var cont = $(this), elem = cont.find('.parallax-image'), cont_top = cont.offset().top, cont_h = cont.height(), elem_h = Math.round(cont_h * 1.3), diff = elem_h - cont_h, max = Math.max(cont_h, win_h), speed = diff / max, parallaxer = { cont_top: cont_top, cont_h: cont_h, elem: elem, speed: speed }; parallax_objs.push(parallaxer); }); } function on_scroll() { if (!scroll_busy) { scroll_busy = true; window.requestAnimationFrame(init_scroll); } } function init_scroll() { scroll_events() scroll_busy = false; } function scroll_events() { var win_top = win.scrollTop(), win_btm = win_top + win_h; $.each(parallax_objs, function(i, para) { cont_btm = para.cont_top + para.cont_h; if( cont_btm > win_top && para.cont_top <= win_btm ) { var cont_scrolled = win_top - para.cont_top - para.cont_h, value = Math.round(cont_scrolled * para.speed); para.elem.css('top', value + 'px'); } }); } $(document).ready(function() { init_parallax(); win.resize(init_parallax); scroll_events(); win.scroll(on_scroll); }); })(jQuery); .parallax-window { min-height: 300px; position: relative; overflow: hidden; } .parallax-window.lg { min-height: 600px; } .parallax-image { position: absolute; top: 0; left: 0; width: 100%; height: 130%; background-size: cover; background-repeat: no-repeat; background-position: 50% 50%; transform: translate3d(0, 0, 0); z-index: -1; } .image-1 { background-image: url(https://i.ytimg.com/vi/TbC-vUPMR7k/maxresdefault.jpg); } .image-2 { background-image: url(https://i.ytimg.com/vi/xi5-YrAEChc/maxresdefault.jpg); } .parallax-content { position: absolute; top: 50%; left: 0; width: 100%; text-align: center; font-family: arial, sans-serif; font-size: 60px; color: #fff; transform: translateY(-50%); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="parallax-window lg"> <div class="parallax-image image-1"></div> <div class="parallax-content">Hello World</div> </div> <div class="parallax-window"> <div class="parallax-image image-2"></div> <div class="parallax-content">Hello World</div> </div> <div class="parallax-window lg"> <div class="parallax-image image-1"></div> <div class="parallax-content">Hello World</div> </div> <div class="parallax-window"> <div class="parallax-image image-2"></div> <div class="parallax-content">Hello World</div> </div> <div class="parallax-window lg"> <div class="parallax-image image-1"></div> <div class="parallax-content">Hello World</div> </div> Updated Fiddle: https://jsfiddle.net/8dwLwgy7/2/
Magnific Popup with upload image preview
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>
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!