I think I'm doing something wrong in the variables or syntax... i don't know, help me to correct my code. (I'm using Leaflet for the map show)
Desired Behavior
The user should be able to see the BBOX entering the coordinates into the URL, for example:
.com/#013.0,052.0,013.5,052.5
I only care that the BBOX is shown, I don't care that the URL coordinates change when zooming or moving around the map.
My HTML
<!DOCTYPE html>
<html>
<header>
<link rel="stylesheet" href="style.css" />
<link
rel="stylesheet"
href="https://unpkg.com/leaflet#1.9.3/dist/leaflet.css"
integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
crossorigin=""
/>
<script
src="https://unpkg.com/leaflet#1.9.3/dist/leaflet.js"
integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM="
crossorigin=""
></script>
</header>
<body>
<div id="map"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://unpkg.com/leaflet#1.0.1/dist/leaflet.js"></script>
<script src="leaflet-hash.js"></script>
<script>
var map = L.map("map").setView([42, 12], 4);
// var hash = new L.hash(map);
var urlhash = window.location.hash.substring(1).split("/");
var boundingBox = "";
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 22,
minZoom: 1,
continuousWorld: false,
noWrap: false,
attribution:
'Data by OpenStreetMap, under ODbL.',
detectRetina: false,
}).addTo(map);
var bboxField = L.control({
position: "bottomleft",
});
bboxField.onAdd = function (map) {
//create div container for control
var div = L.DomUtil.create("div", "myButtonBar");
//prevent mouse events from propagating through to the map
L.DomEvent.disableClickPropagation(div);
//create custom radio buttons
div.innerHTML =
'BBOX (Left (LON) ,Bottom (LAT), Right (LON), Top (LAT), comma separated, with or without decimal point):<br><input type="text" id="bbox_field"/><button id="setDimensions">Display BBOX</button><button id="remove">Remove</button>';
return div;
};
bboxField.addTo(map);
$(".myButtonBar").css("font-weight", "bold");
if (urlhash[0] !== "") {
$("#bbox_field").val(urlhash[0]);
draw_bbox(urlhash[0]);
}
function draw_bbox(box) {
var myarray = box.split(",");
var bounds = [
[myarray[1], myarray[0]],
[myarray[3], myarray[2]],
];
boundingBox = L.rectangle(bounds, { color: "#ff7800", weight: 1 });
map.removeLayer(boundingBox);
boundingBox.addTo(map);
map.fitBounds(boundingBox.getBounds());
map.setZoom(map.getZoom() - 1);
}
$("#setDimensions").click(function () {
draw_bbox($("#bbox_field").val());
});
$("#bbox_field").keyup(function (event) {
if (event.keyCode === 13) {
$("#setDimensions").click();
}
});
// console.log(bbox)
$("#remove").click(function () {
map.removeLayer(boundingBox);
});
</script>
</body>
</html>
Leaflet Hash Plugin Code
(function(window) {
var HAS_HASHCHANGE = (function() {
var doc_mode = window.documentMode;
return ('onhashchange' in window) &&
(doc_mode === undefined || doc_mode > 7);
})();
L.hash = function(map) {
this.onHashChange = L.Util.bind(this.onHashChange, this);
if (map) {
this.init(map);
}
};
L.hash.parseHash = function(hash) {
if(hash.indexOf('#') === 0) {
hash = hash.substr(1);
}
var args = hash.split("/");
if (args.length == 3) {
var zoom = parseInt(args[0], 10),
lat = parseFloat(args[1]),
lon = parseFloat(args[2]);
if (isNaN(zoom) || isNaN(lat) || isNaN(lon)) {
return false;
} else {
return {
center: new L.LatLng(lat, lon),
zoom: zoom
};
}
} else {
return false;
}
};
L.hash.formatHash = function(map) {
var center = map.getCenter(),
zoom = map.getZoom(),
precision = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2));
return "#" + [zoom,
center.lat.toFixed(precision),
center.lng.toFixed(precision)
].join("/");
},
L.hash.prototype = {
map: null,
lastHash: null,
parseHash: L.hash.parseHash,
formatHash: L.hash.formatHash,
init: function(map) {
this.map = map;
// reset the hash
this.lastHash = null;
this.onHashChange();
if (!this.isListening) {
this.startListening();
}
},
removeFrom: function(map) {
if (this.changeTimeout) {
clearTimeout(this.changeTimeout);
}
if (this.isListening) {
this.stopListening();
}
this.map = null;
},
onMapMove: function() {
// bail if we're moving the map (updating from a hash),
// or if the map is not yet loaded
if (this.movingMap || !this.map._loaded) {
return false;
}
var hash = this.formatHash(this.map);
if (this.lastHash != hash) {
location.replace(hash);
this.lastHash = hash;
}
},
movingMap: false,
update: function() {
var hash = location.hash;
if (hash === this.lastHash) {
return;
}
var parsed = this.parseHash(hash);
if (parsed) {
this.movingMap = true;
this.map.setView(parsed.center, parsed.zoom);
this.movingMap = false;
} else {
this.onMapMove(this.map);
}
},
// defer hash change updates every 100ms
changeDefer: 100,
changeTimeout: null,
onHashChange: function() {
// throttle calls to update() so that they only happen every
// `changeDefer` ms
if (!this.changeTimeout) {
var that = this;
this.changeTimeout = setTimeout(function() {
that.update();
that.changeTimeout = null;
}, this.changeDefer);
}
},
isListening: false,
hashChangeInterval: null,
startListening: function() {
this.map.on("moveend", this.onMapMove, this);
if (HAS_HASHCHANGE) {
L.DomEvent.addListener(window, "hashchange", this.onHashChange);
} else {
clearInterval(this.hashChangeInterval);
this.hashChangeInterval = setInterval(this.onHashChange, 50);
}
this.isListening = true;
},
stopListening: function() {
this.map.off("moveend", this.onMapMove, this);
if (HAS_HASHCHANGE) {
L.DomEvent.removeListener(window, "hashchange", this.onHashChange);
} else {
clearInterval(this.hashChangeInterval);
}
this.isListening = false;
}
};
L.hash = function(map) {
return new L.hash(map);
};
L.map.prototype.addHash = function() {
this._hash = L.hash(this);
};
L.map.prototype.removeHash = function() {
this._hash.removeFrom();
};
})(window);
L.interpolatePosition = function(p1, p2, duration, t) {
var k = t/duration;
k = (k > 0) ? k : 0;
k = (k > 1) ? 1 : k;
return L.latLng(p1.lat + k * (p2.lat - p1.lat),
p1.lng + k * (p2.lng - p1.lng));
};
L.Marker.MovingMarker = L.Marker.extend({
//state constants
statics: {
notStartedState: 0,
endedState: 1,
pausedState: 2,
runState: 3
},
options: {
autostart: false,
loop: false,
},
initialize: function (latlngs, durations, options) {
L.Marker.prototype.initialize.call(this, latlngs[0], options);
this._latlngs = latlngs.map(function(e, index) {
return L.latLng(e);
});
if (durations instanceof Array) {
this._durations = durations;
} else {
this._durations = this._createDurations(this._latlngs, durations);
}
this._currentDuration = 0;
this._currentIndex = 0;
this._state = L.Marker.MovingMarker.notStartedState;
this._startTime = 0;
this._startTimeStamp = 0; // timestamp given by requestAnimFrame
this._pauseStartTime = 0;
this._animId = 0;
this._animRequested = false;
this._currentLine = [];
this._stations = {};
},
isRunning: function() {
return this._state === L.Marker.MovingMarker.runState;
},
isEnded: function() {
return this._state === L.Marker.MovingMarker.endedState;
},
isStarted: function() {
return this._state !== L.Marker.MovingMarker.notStartedState;
},
isPaused: function() {
return this._state === L.Marker.MovingMarker.pausedState;
},
start: function() {
if (this.isRunning()) {
return;
}
if (this.isPaused()) {
this.resume();
} else {
this._loadLine(0);
this._startAnimation();
this.fire('start');
}
},
resume: function() {
if (! this.isPaused()) {
return;
}
// update the current line
this._currentLine[0] = this.getLatLng();
this._currentDuration -= (this._pauseStartTime - this._startTime);
this._startAnimation();
},
pause: function() {
if (! this.isRunning()) {
return;
}
this._pauseStartTime = Date.now();
this._state = L.Marker.MovingMarker.pausedState;
this._stopAnimation();
this._updatePosition();
},
stop: function(elapsedTime) {
if (this.isEnded()) {
return;
}
this._stopAnimation();
if (typeof(elapsedTime) === 'undefined') {
// user call
elapsedTime = 0;
this._updatePosition();
}
this._state = L.Marker.MovingMarker.endedState;
this.fire('end', {elapsedTime: elapsedTime});
},
addLatLng: function(latlng, duration) {
this._latlngs.push(L.latLng(latlng));
this._durations.push(duration);
},
moveTo: function(latlng, duration) {
this._stopAnimation();
this._latlngs = [this.getLatLng(), L.latLng(latlng)];
this._durations = [duration];
this._state = L.Marker.MovingMarker.notStartedState;
this.start();
this.options.loop = false;
},
addStation: function(pointIndex, duration) {
if (pointIndex > this._latlngs.length - 2 || pointIndex < 1) {
return;
}
this._stations[pointIndex] = duration;
},
onAdd: function (map) {
L.Marker.prototype.onAdd.call(this, map);
if (this.options.autostart && (! this.isStarted())) {
this.start();
return;
}
if (this.isRunning()) {
this._resumeAnimation();
}
},
onRemove: function(map) {
L.Marker.prototype.onRemove.call(this, map);
this._stopAnimation();
},
_createDurations: function (latlngs, duration) {
var lastIndex = latlngs.length - 1;
var distances = [];
var totalDistance = 0;
var distance = 0;
// compute array of distances between points
for (var i = 0; i < lastIndex; i++) {
distance = latlngs[i + 1].distanceTo(latlngs[i]);
distances.push(distance);
totalDistance += distance;
}
var ratioDuration = duration / totalDistance;
var durations = [];
for (i = 0; i < distances.length; i++) {
durations.push(distances[i] * ratioDuration);
}
return durations;
},
_startAnimation: function() {
this._state = L.Marker.MovingMarker.runState;
this._animId = L.Util.requestAnimFrame(function(timestamp) {
this._startTime = Date.now();
this._startTimeStamp = timestamp;
this._animate(timestamp);
}, this, true);
this._animRequested = true;
},
_resumeAnimation: function() {
if (! this._animRequested) {
this._animRequested = true;
this._animId = L.Util.requestAnimFrame(function(timestamp) {
this._animate(timestamp);
}, this, true);
}
},
_stopAnimation: function() {
if (this._animRequested) {
L.Util.cancelAnimFrame(this._animId);
this._animRequested = false;
}
},
_updatePosition: function() {
var elapsedTime = Date.now() - this._startTime;
this._animate(this._startTimeStamp + elapsedTime, true);
},
_loadLine: function(index) {
this._currentIndex = index;
this._currentDuration = this._durations[index];
this._currentLine = this._latlngs.slice(index, index + 2);
},
/**
* Load the line where the marker is
* #param {Number} timestamp
* #return {Number} elapsed time on the current line or null if
* we reached the end or marker is at a station
*/
_updateLine: function(timestamp) {
// time elapsed since the last latlng
var elapsedTime = timestamp - this._startTimeStamp;
// not enough time to update the line
if (elapsedTime <= this._currentDuration) {
return elapsedTime;
}
var lineIndex = this._currentIndex;
var lineDuration = this._currentDuration;
var stationDuration;
while (elapsedTime > lineDuration) {
// substract time of the current line
elapsedTime -= lineDuration;
stationDuration = this._stations[lineIndex + 1];
// test if there is a station at the end of the line
if (stationDuration !== undefined) {
if (elapsedTime < stationDuration) {
this.setLatLng(this._latlngs[lineIndex + 1]);
return null;
}
elapsedTime -= stationDuration;
}
lineIndex++;
// test if we have reached the end of the polyline
if (lineIndex >= this._latlngs.length - 1) {
if (this.options.loop) {
lineIndex = 0;
this.fire('loop', {elapsedTime: elapsedTime});
} else {
// place the marker at the end, else it would be at
// the last position
this.setLatLng(this._latlngs[this._latlngs.length - 1]);
this.stop(elapsedTime);
return null;
}
}
lineDuration = this._durations[lineIndex];
}
this._loadLine(lineIndex);
this._startTimeStamp = timestamp - elapsedTime;
this._startTime = Date.now() - elapsedTime;
return elapsedTime;
},
_animate: function(timestamp, noRequestAnim) {
this._animRequested = false;
// find the next line and compute the new elapsedTime
var elapsedTime = this._updateLine(timestamp);
if (this.isEnded()) {
// no need to animate
return;
}
if (elapsedTime != null) {
// compute the position
var p = L.interpolatePosition(this._currentLine[0],
this._currentLine[1],
this._currentDuration,
elapsedTime);
this.setLatLng(p);
}
if (! noRequestAnim) {
this._animId = L.Util.requestAnimFrame(this._animate, this, false);
this._animRequested = true;
}
}
});
L.Marker.movingMarker = function (latlngs, duration, options) {
return new L.Marker.MovingMarker(latlngs, duration, options);
};
I’m still new with JS and I have this problem. I was working on a js that I got from GitHub
https://github.com/ewoken/Leaflet.MovingMarker. Its a project where you have animated markers moving from a to b. I trying to demonstrate a transport environment for my thesis and I wrote my own functions to it.
function train_station(number){
const countries_train = [];
countries_train[1] = [71, "Germany", "Munich", 48.1351, 11.582, "Train Stration", "Europe"]
countries_train[2] = [72, "England", "London", 51.5074, 0.1278, "Train Stration", "Europe"]
countries_train[3] = [73, "Belgium", "Antwerp", 51.2194, 4.4025, "Train Stration", "Europe"]
countries_train[4] = [74, "France", "Limoges", 45.8336, 1.2611, "Train Stration", "Europe"]
countries_train[5] = [75, "Portugal", "Porto", 41.1579, 8.6291, "Train Stration", "Europe"]
countries_train[6] = [76, "Romania", "Bucharest", 44.4268, 26.1025, "Train Stration", "Europe"]
countries_train[7] = [77, "Italy", "Milan", 45.4642, 9.19, "Train Stration", "Europe"]
return countries_train[number]}
function europe_island(number) {
const countries_island = [];
countries_island[1] = [21, "Iceland", "Reykjavik", 64.1466, 21.9426, "Island", "Europe"]
countries_island[2] = [22, "Ireland", "Dublin", 53.3498, 6.2603, "Island", "Europe"]
return countries_island[number]}
export {europe_core, europe_island, europe_uk, train_station, harbour, europe_scandinavia, international}
Thats my function. I have other function but the structure is the same and the js file I want to implement it in is this:
So, I was trying to implement my function in the script.js file from the GitHub link and every time I import a function of mine the script doesn’t
var map = new L.Map('map', {
zoom: 6,
minZoom: 3,
});
var tileUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', layer = new L.TileLayer(tileUrl,
{
attribution: 'Maps © OpenStreetMap contributors',
maxZoom: 18
});
map.addLayer(layer);
var parisKievLL = [[48.8567, 2.3508], [50.45, 30.523333]]
var londonParisRomeBerlinBucarest = [[51.507222, -0.1275], [48.8567, 2.3508],
[41.9, 12.5], [52.516667, 13.383333], [44.4166, 26.1]]
var londonBrusselFrankfurtAmsterdamLondon = [[51.507222, -0.1275], [50.85, 4.35],
[50.116667, 8.683333], [52.366667, 4.9], [51.507222, -0.1275]];
var barcelonePerpignanPauBordeauxMarseilleMonaco = [
[41.385064, 2.173403],
[42.698611, 2.895556],
[43.3017, -0.3686],
[44.837912, -0.579541],
[43.296346, 5.369889],
[43.738418, 7.424616]
];
map.fitBounds(londonParisRomeBerlinBucarest);
var marker1 = L.Marker.movingMarker(parisKievLL, [10000]).addTo(map);
L.polyline(parisKievLL).addTo(map);
marker1.once('click', function () {
marker1.start();
marker1.closePopup();
marker1.unbindPopup();
marker1.on('click', function () {
if (marker1.isRunning()) {
marker1.pause();
} else {
marker1.start();
}
});
setTimeout(function () {
marker1.bindPopup('<b>Click me to pause !</b>').openPopup();
}, 2000);
});
marker1.bindPopup('<b>Click me to start !</b>', {closeOnClick: false});
marker1.openPopup();
var marker2 = L.Marker.movingMarker(londonParisRomeBerlinBucarest, [3000, 9000, 9000, 4000], {autostart: true}).addTo(map);
L.polyline(londonParisRomeBerlinBucarest, {color: 'red'}).addTo(map);
marker2.on('end', function () {
marker2.bindPopup(message(), {closeOnClick: false})
.openPopup();
});
var marker3 = L.Marker.movingMarker(londonBrusselFrankfurtAmsterdamLondon,
[2000, 2000, 2000, 2000], {autostart: true, loop: true}).addTo(map);
marker3.loops = 0;
marker3.bindPopup('', {closeOnClick: false});
var marker4 = L.Marker.movingMarker([[45.816667, 15.983333]], []).addTo(map);
marker3.on('loop', function (e) {
marker3.loops++;
if (e.elapsedTime < 50) {
marker3.getPopup().setContent("<b>Loop: " + marker3.loops + "</b>")
marker3.openPopup();
setTimeout(function () {
marker3.closePopup();
if (!marker1.isEnded()) {
marker1.openPopup();
} else {
if (marker4.getLatLng().equals([45.816667, 15.983333])) {
marker4.bindPopup('Click on the map to move me !');
marker4.openPopup();
}
}
}, 2000);
}
});
map.on("click", function (e) {
marker4.moveTo(e.latlng, 2000);
});
var marker5 = L.Marker.movingMarker(barcelonePerpignanPauBordeauxMarseilleMonaco, 10000, {autostart: true}).addTo(map);
marker5.addStation(1, 2000);
marker5.addStation(2, 2000);
marker5.addStation(3, 2000);
marker5.addStation(4, 2000);
L.polyline(barcelonePerpignanPauBordeauxMarseilleMonaco,
{color: 'green'}).addTo(map);
<!DOCTYPE html>
<html>
<head>
<title> Leaflet.MovingMarker Demo Page </title>
<meta charset="UTF-8">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="description" content="Leaflet plugin to animate marker !">
<meta name="keywords" content="Leaflet MovingMarker marker ewoken github animation">
<meta name="author" content="Ewoken">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<main>
<h1> Demo of Leaflet.MovingMarker </h1>
<section>
<div id="map">
</div>
</section>
</main>
<script type="text/javascript" src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script type="text/javascript" src="MovingMarker.js"></script>
<script type="text/javascript" src="script.js">
</script>
</body>
</html>
work anymore.
It shows that "referenceerror L is not defined" and if I do the "Import * as L from 'leaflet'" is says that "referenceerror: window is not defined"
I havent changed the code, it’s just the imports. As soon as I type import the variables in the script turn from purple to grey and dont work anymore.
Im using IntelliJ 2021 IDE Ultimate 2021
I have the type:module in my dependencies so the Imports and exports work.
I change it module on the html file as well
I deleted the folder and reinstalled everything again
Thanks for your time and help guys.
I am working on a library which does DOM hide and show based on other DOM elements.
I have written a basic structure for the library.
The below is the code to handle DOM elements hiding when a checkbox is checked and unchecked.
My overall goal is to make this library extensible and maintainable.
Am I following SOLID principles? Is there any better way to do it? Are there any design patterns to follow?
// basic data structure of config object
var rules = [
{
sourceId: 'mainCheckbox',
targetId: 'exampleDiv1',
ruleType: 'onlyOnChecked',
targetVisibilityOnChecked: 'hide', // show / hide
targetVisibilityOnUnchecked: 'show',
doNotReset: false
}
]
var ruleToProcessorMap = {
onlyOnChecked: OnlyOnCheckedRuleProcessor
}
var RuleEngine = {}
RuleEngine.run = function(rules) {
var ruleIndex
for (ruleIndex = 0; ruleIndex < rules.length; rules++) {
this.processRule(rules[ruleIndex])
}
}
RuleEngine.processRule = function(ruleObj) {
var ruleProcessor = new ruleToProcessorMap[ruleObj.ruleType](ruleObj)
ruleProcessor.process()
}
function OnlyOnCheckedRuleProcessor(options) {
this.options = options || {}
}
OnlyOnCheckedRuleProcessor.prototype.process = function() {
var $sourceId = $id(this.options.sourceId),
ctx = this
$sourceId.on('click', onSourceClick)
function onSourceClick() {
var elementVisibilityHandler = new ElementVisibilityHandler({
elementId: ctx.options.targetId,
doNotReset: ctx.options.doNotReset
}),
show = elementVisibilityHandler.show,
hide = elementVisibilityHandler.hide
var visibilityMap = {
show: show,
hide: hide
}
var onCheckedFunc = visibilityMap[ctx.options.targetVisibilityOnChecked]
var onUncheckedFunc = visibilityMap[ctx.options.targetVisibilityOnUnchecked]
if ($sourceId.is(':checked')) {
onCheckedFunc.call(elementVisibilityHandler)
} else {
onUncheckedFunc.call(elementVisibilityHandler)
}
}
}
function ElementVisibilityHandler(options) {
this.options = options || {}
this.$element = $id(options.elementId)
}
ElementVisibilityHandler.prototype.show = function() {
if (isContainerElement(this.$element)) {
if (this.options.doNotReset) {
simpleShow(this.$element)
} else {
showWithChildren(this.$element)
}
}
}
ElementVisibilityHandler.prototype.hide = function() {
if (isContainerElement(this.$element)) {
if (this.options.doNotReset) {
simpleHide(this.$element)
} else {
hideAndResetChildren(this.$element)
}
}
}
function simpleHide($element) {
return $element.hide()
}
function hideAndResetChildren($element) {
var $children = simpleHide($element)
.children()
.hide()
$children.find('input:checkbox').prop('checked', false)
$children.find('textarea, input').val('')
}
function simpleShow($element) {
return $element.show()
}
function showWithChildren($element) {
simpleShow($element)
.children()
.show()
}
function $id(elementId) {
return $('#' + elementId)
}
function isContainerElement($element) {
if (typeof $element === 'string') {
$element = $id($element)
}
return $element.prop('tagName').toLowerCase()
}
// execution starts here
RuleEngine.run(rules)
Recently I want to start a project by piggyback someone's extension. I want to scope one of the image source (local variable, a base64 url) and then photo recognize it on the popup page. I keep getting error "imgb64.replace is not a function" or "imgb64" not defined.
like my title said, I want to scope the local variable in.in.inside a function (from backgound.js )and use it globally (or in popup.js). very new to this, please help guys.
// this is popup.js
chrome.runtime.getBackgroundPage(function(bg) {
bg.capture(window);
});
/// what I did
function img_find() {
var imgs = document.getElementsByTagName("img");
var imgSrcs = [];
for (var i = 0; i < imgs.length; i++) {
imgSrcs.push(imgs[i].src);
}
return imgSrcs;
}
var imgb64 = img_find();
try {
const app = new Clarifai.App({
apiKey: 'mykey'
});
}
catch(err) {
alert("Need a valid API Key!");
throw "Invalid API Key";
}
// Checks for valid image type
function validFile(imageName) {
var lowerImageName = imageName.toLowerCase();
return lowerImageName.search(/jpg|png|bmp|tiff/gi) != -1;
}
var imageDetails = imgb64.replace(/^data:image\/(.*);base64,/, '');
console.log(imageDetails)
app.models.predict("e466caa0619f444ab97497640cefc4dc", {base64:
imageDetails}).then(
function(response) {
// do something with response
},
function(err) {
// there was an error
}
);
/// end what I did
below is background.js, I think what I need is the local var img.src, thats all.
function capture(popup) {
function callOnLoad(func) {
popup.addEventListener("load", func);
if (popup.document.readyState === "complete") {
func();
}
}
crxCS.insert(null, { file: "capture.js" }, function() {
crxCS.callA(null, "get", function(result) {
var scrShot, zm, bufCav, bufCavCtx;
function mkImgList() {
for (var i = 0; i < result.vidShots.length; i++) {
var img = new popup.Image();
img.onload = function() {
this.style.height = this.naturalHeight /
(this.naturalWidth / 400) + "px";
};
if (result.vidShots[i].constructor === String) {
img.src = result.vidShots[i];
} else {
bufCav.width = result.vidShots[i].width * zm;
bufCav.height = result.vidShots[i].height * zm;
bufCavCtx.drawImage(scrShot, -result.vidShots[i].left *
zm, -result.vidShots[i].top * zm);
img.src = bufCav.toDataURL('image/png');
////// maybe clarifai here ?
////end clarifai
}
popup.document.body.appendChild(img);
}
popup.onclick = function(mouseEvent) {
if (mouseEvent.target.tagName === "IMG") {
chrome.downloads.download({ url: mouseEvent.target.src,
saveAs: true, filename: "chrome_video_capture_" + (new Date()).getTime() +
".png" });
}
};
popup.onunload = function(mouseEvent) {
crxCS.callA(null, "rcy");
};
} /// end mkImgList
if (result.needScrShot) {
bufCav = popup.document.createElement("canvas");
bufCavCtx = bufCav.getContext("2d");
chrome.tabs.captureVisibleTab({ format: "png" },
function(dataUrl) {
scrShot = new Image();
scrShot.onload = function() {
chrome.tabs.getZoom(function(zoomFactor) {
zm = zoomFactor;
callOnLoad(function() {
mkImgList(zoomFactor);
});
});
};
scrShot.src = dataUrl;
});
} else if (result.vidShots.length) {
callOnLoad(mkImgList);
} else {
popup.document.body.appendChild(notFound);
}
}); // end crxCS.callA
}); // end crxCS.insert
} // end capture
Please help guys. :)
here is my problem :)
i try to add "Apprise-v2" plugin to my website,
i include both files, css and js, this way :
<!--TOP OF MY PAGE-->
<html>
<body>
<link rel="stylesheet" type="text/css" href="css/apprise-v2.css"/>
<!--MY PAGE CONTENTS...-->
...........
<!--BOTTOM OF MY PAGE-->
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/raphael-min.js"></script>
<script src="js/tablesorter/jquery.tablesorter.js"></script>
<script src="js/tablesorter/tables.js"></script>
<script type="text/javascript" src="JS/jquery.fancybox.js"></script>
<script type="text/javascript" src="JS/jquery.fancybox.pack.js"></script>
<script src='js/apprise-v2.js'></script>
<script>Apprise("test");</script>
</body>
</html>
my firebug warns me with this :
TypeError: $Apprise is null
if($Apprise.is(':visible')) {
Thanks for help! :)
EDIT : Here is the apprise-v2.js file contents :
// Global Apprise variables
var $Apprise = null,
$overlay = null,
$body = null,
$window = null,
$cA = null,
AppriseQueue = [];
// Add overlay and set opacity for cross-browser compatibility
$(function() {
$Apprise = $('<div class="apprise">');
$overlay = $('<div class="apprise-overlay">');
$body = $('body');
$window = $(window);
$body.append( $overlay.css('opacity', '.94') ).append($Apprise);
});
function Apprise(text, options) {
// Restrict blank modals
if(text===undefined || !text) {
return false;
}
// Necessary variables
var $me = this,
$_inner = $('<div class="apprise-inner">'),
$_buttons = $('<div class="apprise-buttons">'),
$_input = $('<input type="text">');
// Default settings (edit these to your liking)
var settings = {
animation: 700, // Animation speed
buttons: {
confirm: {
action: function() { $me.dissapear(); }, // Callback function
className: null, // Custom class name(s)
id: 'confirm', // Element ID
text: 'Ok' // Button text
}
},
input: false, // input dialog
override: true // Override browser navigation while Apprise is visible
};
// Merge settings with options
$.extend(settings, options);
// Close current Apprise, exit
if(text=='close') {
$cA.dissapear();
return;
}
// If an Apprise is already open, push it to the queue
if($Apprise.is(':visible')) {
AppriseQueue.push({text: text, options: settings});
return;
}
// Width adjusting function
this.adjustWidth = function() {
var window_width = $window.width(), w = "20%", l = "40%";
if(window_width<=800) {
w = "90%", l = "5%";
} else if(window_width <= 1400 && window_width > 800) {
w = "70%", l = "15%";
} else if(window_width <= 1800 && window_width > 1400) {
w = "50%", l = "25%";
} else if(window_width <= 2200 && window_width > 1800) {
w = "30%", l = "35%";
}
$Apprise.css('width', w).css('left', l);
};
// Close function
this.dissapear = function() {
$Apprise.animate({
top: '-100%'
},
settings.animation, function() {
$overlay.fadeOut(300);
$Apprise.hide();
// Unbind window listeners
$window.unbind("beforeunload");
$window.unbind("keydown");
// If in queue, run it
if(AppriseQueue[0]) {
Apprise(AppriseQueue[0].text, AppriseQueue[0].options);
AppriseQueue.splice(0,1);
}
});
return;
};
// Keypress function
this.keyPress = function() {
$window.bind('keydown', function(e) {
// Close if the ESC key is pressed
if(e.keyCode===27) {
if(settings.buttons.cancel) {
$("#apprise-btn-" + settings.buttons.cancel.id).trigger('click');
} else {
$me.dissapear();
}
} else if(e.keyCode===13) {
if(settings.buttons.confirm) {
$("#apprise-btn-" + settings.buttons.confirm.id).trigger('click');
} else {
$me.dissapear();
}
}
});
};
// Add buttons
$.each(settings.buttons, function(i, button) {
if(button) {
// Create button
var $_button = $('<button id="apprise-btn-' + button.id + '">').append(button.text);
// Add custom class names
if(button.className) {
$_button.addClass(button.className);
}
// Add to buttons
$_buttons.append($_button);
// Callback (or close) function
$_button.on("click", function() {
// Build response object
var response = {
clicked: button, // Pass back the object of the button that was clicked
input: ($_input.val() ? $_input.val() : null) // User inputted text
};
button.action( response );
//$me.dissapear();
});
}
});
// Disabled browser actions while open
if(settings.override) {
$window.bind('beforeunload', function(e){
return "An alert requires attention";
});
}
// Adjust dimensions based on window
$me.adjustWidth();
$window.resize( function() { $me.adjustWidth() } );
// Append elements, show Apprise
$Apprise.html('').append( $_inner.append('<div class="apprise-content">' + text + '</div>') ).append($_buttons);
$cA = this;
if(settings.input) {
$_inner.find('.apprise-content').append( $('<div class="apprise-input">').append( $_input ) );
}
$overlay.fadeIn(300);
$Apprise.show().animate({
top: '20%'
},
settings.animation,
function() {
$me.keyPress();
}
);
// Focus on input
if(settings.input) {
$_input.focus();
}
} // end Apprise();
Make call after page loaded.
$(function() {
Apprise('hi there');
});
I think using Apprise V3 is a better idea.
https://github.com/exis9/Apprise_V3