MooTools - how to reload image? - image

Is there any way to reload the same image using mootools. I have a camera that gives me image, but I have to refresh it. I wrote this, but it doesn't work so well:
var url = "some valid url to some image.jpg";
var timer = 10;
var periodical;
var camera_container;
var refresh = (function() {
var loader = new Asset.image(url, {
onLoad : function() {
camera_container.empty();
camera_container.inject(loader);
}
});
});
window.addEvent('domready', function() {
// the periodical starts here, the * 1000 is because milliseconds required
refresh.periodical(timer * 1000, this);
camera_container = $('camera-image');
});
Any help appreciated. Thanks.

why not add a seeding bit to the url?
(function() {
var url = "some valid url to some image.jpg?";
this.timer = 10;
var counter = 0;
this.refresh = (function() {
var loader = new Asset.image(url + counter, {
onLoad: function() {
camera_container.empty();
camera_container.inject(loader);
counter++;
}
});
});
})();
window.addEvent('domready', function() {
// the periodical starts here, the * 1000 is because milliseconds required
refresh.periodical(timer * 1000, this);
this.camera_container = $('camera-image');
});
this way the url will always be path/image.jpg?n where n changes and will force the browser to re-fetch it.

I think something like this also can work:
<div id="image-holder">
<img src="http://www.image.com/image.jpg"/>
</div>
var srcImage = 'http://www.image.com/image.jpg';
var reloadTime = 4000;
var holder = document.id('image-holder');
var imageReload = function(){
holder.empty();
var newImage = new Element('img',{
id:'image',
src:srcImage ,
alt:'image new'
}).inject(holder);
}
var start = function() {
interval = imageReload.periodical(reloadTime);
};
start();

Related

Moving element on Window scroll

You'll see in this JsFiddle https://jsfiddle.net/xpvt214o/402281/ there is an image scrolling within another one on window scroll.
How can I modify the below so that it doesn't start scrolling until it hits that element (after all the br tags)?
I've tried offsetting it but not getting anywhere.
It would also be fine if it just scrolled a lot slower.
jQuery(document).ready(
function() {
var $w = $(window);
var $d = $('.oh');
$(window).scroll(function(event) {
var st = $w.scrollTop();
_x = st;
lastScrollTop = st;
$d.css('bottom', _x);
});
});
Here's an example of what I'm trying to achieve https://www.sketchapp.com/
I found this which does what I'm looking for
https://codepen.io/JTParrett/pen/BkDie
$.fn.moveIt = function(){
var $window = $(window);
var instances = [];
$(this).each(function(){
instances.push(new moveItItem($(this)));
});
window.addEventListener('scroll', function(){
var scrollTop = $window.scrollTop();
instances.forEach(function(inst){
inst.update(scrollTop);
});
}, {passive: true});
}
var moveItItem = function(el){
this.el = $(el);
this.speed = parseInt(this.el.attr('data-scroll-speed'));
};
moveItItem.prototype.update = function(scrollTop){
this.el.css('transform', 'translateY(' + -(scrollTop / this.speed) +
'px)');
};
// Initialization
$(function(){
$('[data-scroll-speed]').moveIt();
});

OpenLayers3 : Draggable OverviewMapControl

In OpenLayers 2, in the OverviewMapControl, you can drag the "box" to move the map.
You can not do this in OpenLayers 3.
I've tried to implement a custom control based on https://github.com/openlayers/ol3/blob/master/src/ol/control/overviewmapcontrol.js, but you can not use goog.xxx or other fancy stuff like ol.extent.scaleFromCenter when you are not in debug !
How should I proceed ?
basically, implementing drag'n drop is fairly "simple" :
var dragging = null;
var getMap = this.getMap.bind(this); //during ctor of a control, we have no access to the map !
$(document.body).on("mousemove", function (e) {
if (dragging) {
dragging.el.offset({
top: e.pageY,
left: e.pageX
});
}
});
$(box).on("mousedown", function (e) {
dragging = {
el: $(e.target)
};
});
$(document.body).on("mouseup", function (e) {
if (dragging) {
debugger;
var coords = ovmap.getEventCoordinate(e.originalEvent);
//TODO: taking event coordinates is not good, we must use center of the box coordinates
//the problem is that ovmap.getCoordinateFromPixel(dragging.el.offset()) is not working at all because we need to adjust ovmap viewport
getMap().getView().setCenter(coords);
dragging = null;
}
});
For those interested (which does not seem to be the case at the moment :)), here is the way I solved
/**
* Mostly a big copy/paste from https://raw.githubusercontent.com/openlayers/ol3/master/src/ol/control/overviewmapcontrol.js
* without rotation and zoom/dezoom plus some adapations from http://ol3.qtibia.ro/build/examples/overviewmap-custom-drag.html
* to add the possibility to drag the box on the minimap to move the main map
*/
ol.control.CustomOverviewMap = function (opt_options) {
var options = typeof opt_options !== 'undefined' ? opt_options : {};
this.collapsed_ = typeof options.collapsed !== 'undefined' ? options.collapsed : true;
this.onCollapseOrExpand = options.onCollapseOrExpand || function () { };
this.needFirstRenderUpdate_ = this.collapsed_; //prepare the hack to render the map when uncollapsed the first time
var tipLabel = typeof options.tipLabel !== 'undefined' ? options.tipLabel : 'Overview map';
this.collapseLabel_ = $('<span>\u00BB</span>').get(0);
this.label_ = $('<span>\u00AB</span>').get(0);
var activeLabel = (!this.collapsed_) ? this.collapseLabel_ : this.label_;
var button = $('<button type="button" title="{0}"></button>'.replace('{0}', tipLabel)).append(activeLabel);
button.on('click', this.handleClick_.bind(this));
//ol.control.Control.bindMouseOutFocusOutBlur(button);
button.on('mouseout', function () { this.blur(); });
button.on('focusout', function () { this.blur(); });
var ovmapDiv = $('<div class="ol-overviewmap-map"></div>').get(0);
this.ovmap_ = new ol.Map({
controls: new ol.Collection(),
interactions: new ol.Collection(),
layers: [options.tileLayer],
target: ovmapDiv,
view: new ol.View(opt_options.view)
});
var box = $('<div class="ol-overviewmap-box"></div>');
this.boxOverlay_ = new ol.Overlay({
position: [0, 0],
positioning: 'bottom-left',
element: box.get(0)
});
this.ovmap_.addOverlay(this.boxOverlay_);
var cssClasses = 'ol-overviewmap ol-unselectable ol-control' +
(this.collapsed_ ? ' ol-collapsed' : '');
var element = $('<div class="{0}"></div>'.replace('{0}', cssClasses)).append(ovmapDiv).append(button).get(0);
ol.control.Control.call(this, {
element: element,
render: ol.control.CustomOverviewMap.render
});
// deal with dragable minimap
this.dragging = null;
box.on("mousedown", this.onStartDrag.bind(this));
$(document.body).on("mousemove", this.onDrag.bind(this));
$(document.body).on("mouseup", this.onEndDrag.bind(this));
};
ol.inherits(ol.control.CustomOverviewMap, ol.control.Control);
ol.control.CustomOverviewMap.prototype.onStartDrag = function (e) {
// remember some data to use during onDrag or onDragEnd
var box = $(e.target);
this.dragging = {
el: box,
evPos: { top: e.pageY, left: e.pageX },
elPos: box.offset()
};
}
ol.control.CustomOverviewMap.prototype.onDrag = function (e) {
if (this.dragging) {
//set the position of the box to be oldPos+translation(ev)
var curOffset = this.dragging.el.offset();
var newOffset = {
top: curOffset.top + (e.pageY - this.dragging.evPos.top),
left: curOffset.left + (e.pageX - this.dragging.evPos.left)
};
this.dragging.evPos = { top: e.pageY, left: e.pageX };
this.dragging.el.offset(newOffset);
}
}
ol.control.CustomOverviewMap.prototype.onEndDrag = function (e) {
if (this.dragging) {
//see ol3.qtibia.ro href at the top of the class to understand this
var map = this.getMap();
var offset = this.dragging.el.position();
var divSize = [this.dragging.el.width(), this.dragging.el.height()];
var mapSize = map.getSize();
var c = map.getView().getResolution();
var xMove = offset.left * (Math.abs(mapSize[0] / divSize[0]));
var yMove = offset.top * (Math.abs(mapSize[1] / divSize[1]));
var bottomLeft = [0 + xMove, mapSize[1] + yMove];
var topRight = [mapSize[0] + xMove, 0 + yMove];
var left = map.getCoordinateFromPixel(bottomLeft);
var top = map.getCoordinateFromPixel(topRight);
var extent = [left[0], left[1], top[0], top[1]];
map.getView().fitExtent(extent, map.getSize());
map.getView().setResolution(c);
//reset the element at the original position so that when the main map will trigger
//the moveend event, this event will be replayed on the box of the minimap
this.dragging.el.offset(this.dragging.elPos);
this.dragging = null;
}
}
ol.control.CustomOverviewMap.render = function (mapEvent) {
//see original OverviewMap href at the top of the class to understand this
var map = this.getMap();
var ovmap = this.ovmap_;
var mapSize = map.getSize();
var view = map.getView();
var ovview = ovmap.getView();
var overlay = this.boxOverlay_;
var box = this.boxOverlay_.getElement();
var extent = view.calculateExtent(mapSize);
var ovresolution = ovview.getResolution();
var bottomLeft = ol.extent.getBottomLeft(extent);
var topRight = ol.extent.getTopRight(extent);
overlay.setPosition(bottomLeft);
// set box size calculated from map extent size and overview map resolution
if (box) {
var boxWidth = Math.abs((bottomLeft[0] - topRight[0]) / ovresolution);
var boxHeight = Math.abs((topRight[1] - bottomLeft[1]) / ovresolution);
$(box).width(boxWidth).height(boxHeight);
}
};
ol.control.CustomOverviewMap.prototype.handleClick_ = function (event) {
event.preventDefault();
this.collapsed_ = !this.collapsed_;
$(this.element).toggleClass('ol-collapsed');
// change label
if (this.collapsed_) {
this.collapseLabel_.parentNode.replaceChild(this.label_, this.collapseLabel_);
} else {
this.label_.parentNode.replaceChild(this.collapseLabel_, this.label_);
}
// manage overview map if it had not been rendered before and control is expanded
if (!this.collapsed_ && this.needFirstRenderUpdate_) {
this.needFirstRenderUpdate_ = false;
this.ovmap_.updateSize();
this.ovmap_.once("postrender", function () {
this.render();
}.bind(this));
}
//trigger event
this.onCollapseOrExpand(this.collapsed_);
};

How to get Famo.us draggable modifier's render node

I am trying to get parent renderNode of a draggable modifier on 'end' event, is there any api to get a renderNode to which draggable belongs to? My code is as follows :
/*globals define*/
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var Draggable = require("famous/modifiers/Draggable");
var RenderNode = require('famous/core/RenderNode');
/*
* #name DragTest
* #constructor
* #description
*/
function DragTest() {
View.apply(this, arguments);
_createDragSurface.call(this);
}
DragTest.prototype = Object.create(View.prototype);
DragTest.prototype.constructor = DragTest;
DragTest.DEFAULT_OPTIONS = {
};
function _createDragSurface(){
var yOffset=0;
for(var i=0;i<2;i++){
var draggable = new Draggable({
xRange: [-220,0],
yRange: [0,0]
});
var dragSurface= new Surface({
content:'this is a drag surface',
size:[150,150],
properties:{
marginLeft: '10px',
backgroundColor:'grey'
}
});
var dragSurfaceModifier= new StateModifier({
align:[0.5,yOffset]
});
yOffset+=0.3;
dragSurface.pipe(draggable);
draggable.on('end',function(e){
this.setPosition([0,0,0], {
method: 'snap',
period: 300
});
});
var nodePlayer = new RenderNode(draggable);
nodePlayer.add(dragSurfaceModifier).add(dragSurface);
this.add(nodePlayer);
}
}
module.exports = DragTest;
});
On drag of a surface to the left, once it reaches threshold, I want to remove the renderNode i.e.,
draggable.on('end',function(e){
if(e.position[0]<-50){
renderNode.remove()//how to achieve this part of the code as I dont have an access to nodePlayer renderNode here.
}
else{
this.setPosition([0,0,0], {
method: 'snap',
period: 300
});
}
});
If I simply use the name of a renderNode i.e., nodePlayer it will remove the last surface no matter which surface is been dragged.Any input on this is much appreciated.
Best Regards.
There are a lot of ways to accomplish what you want to do.
Since you are using the end event on the draggable and using the position value from the custom event, let's bind the references to the needed items to be able to access them.
There is not a .remove() method on the RenderNode so the example shows a way you could remove a node from the view with a RenderController.
Remember: There is no need to remove nodes from the DOM. Famo.us will manage the renderables in the render tree.
define('main', function(require, exports, module) {
var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var Modifier = require('famous/core/Modifier');
var StateModifier = require('famous/modifiers/StateModifier');
var Draggable = require('famous/modifiers/Draggable');
var TransitionableTransform = require('famous/transitions/TransitionableTransform');
var DragTest = require('DragTest');
var mainContext = Engine.createContext();
var dragTest = new DragTest();
mainContext.add(dragTest);
dragTest.on('removed', function(e) {
console.log('removed ', e.removedNode);
});
});
define('DragTest', function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var Draggable = require("famous/modifiers/Draggable");
var RenderNode = require('famous/core/RenderNode');
var RenderController = require('famous/views/RenderController');
/*
* #name DragTest
* #constructor
* #description
*/
function DragTest() {
View.apply(this, arguments);
_createDragSurface.call(this);
}
DragTest.prototype = Object.create(View.prototype);
DragTest.prototype.constructor = DragTest;
DragTest.DEFAULT_OPTIONS = {};
function _endingDrag(e) {
console.log('end position', e.position, this);
if (e.position[0] < -180) {
this.renderController.hide(this.nodePlayer, function() {
this.surface.emit('removed', {
removedNode: this.nodePlayer
});
}.bind(this));
} else {
this.draggable.setPosition([0, 0, 0], {
duration: 300
});
}
}
function _updatingDrag(e) {
console.log('update position', e.position);
this.surface.setContent('Position ' + e.position);
}
function _createDragSurface() {
var yOffset = 0;
for (var i = 0; i < 2; i++) {
var dragSurface = new Surface({
content: 'this is a drag surface',
size: [150, 150],
properties: {
marginLeft: '10px',
backgroundColor: 'grey'
}
});
var dragSurfaceModifier = new StateModifier({
origin: [0, 0],
align: [0.5, yOffset]
});
yOffset += 0.3;
var draggable = new Draggable({
xRange: [-220, 0],
yRange: [0, 0]
});
var renderController = new RenderController();
this.add(renderController);
var nodePlayer = new RenderNode();
nodePlayer.add(dragSurfaceModifier).add(draggable).add(dragSurface);
renderController.show(nodePlayer)
draggable.on('end', _endingDrag.bind({
draggable: draggable,
renderController: renderController,
nodePlayer: nodePlayer,
surface: dragSurface
}));
draggable.on('update', _updatingDrag.bind({
surface: dragSurface
}));
draggable.subscribe(dragSurface);
dragSurface.pipe(this._eventOutput); // so we can emit a custom removed event to this widget
}
}
module.exports = DragTest;
});
require(['main']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://requirejs.org/docs/release/2.1.16/minified/require.js"></script>
<script src="http://code.famo.us/lib/requestAnimationFrame.js"></script>
<script src="http://code.famo.us/lib/classList.js"></script>
<script src="http://code.famo.us/lib/functionPrototypeBind.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.famo.us/famous/0.3.5/famous.css" />
<script src="http://code.famo.us/famous/0.3.5/famous.min.js"></script>

Adding a .ajaxForm function to standard .ajax call

So I'm trying to find a method of getting a progress bar working on my .ajax call but not having much luck. I know that the ajaxForm plugin has the following code in it that allows for the uploadProgress option but the way my code works I'm not able to use that plugin. Is there anyway of adding the following code somehow so that it attaches to the standard .ajax call? Long shot I know!
// XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
function fileUploadXhr(a) {
var formdata = new FormData();
for (var i=0; i < a.length; i++) {
formdata.append(a[i].name, a[i].value);
}
if (options.extraData) {
var serializedData = deepSerialize(options.extraData);
for (i=0; i < serializedData.length; i++)
if (serializedData[i])
formdata.append(serializedData[i][0], serializedData[i][1]);
}
options.data = null;
var s = $.extend(true, {}, $.ajaxSettings, options, {
contentType: false,
processData: false,
cache: false,
type: method || 'POST'
});
if (options.uploadProgress) {
// workaround because jqXHR does not expose upload property
s.xhr = function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
options.uploadProgress(event, position, total, percent);
}, false);
}
return xhr;
};
}
s.data = null;
var beforeSend = s.beforeSend;
s.beforeSend = function(xhr, o) {
o.data = formdata;
if(beforeSend)
beforeSend.call(this, xhr, o);
};
return $.ajax(s);
}
I do not guarantee on that, but try this:
xhr.upload.onprogress = function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
console.log("Progress: "+percent+"%"); //debug to see if the problem is there
options.uploadProgress(event, position, total, percent);
};
From posted code, I cannot even guess if the problem is in onprogress event handling or that options.uploadProgress, whatever it is.
I posted this as answer only because it wouldn't fit in comment.

Google Map V3: Loading Markers using AJAX+ASP/PHP and Reload on Ruquest or Event

Hi I've searched so many things and found many contents but didn't found what I required actually.
I can loading all markers but unable to Refresh it or Reload it please help me out here's the code:
$(document).ready(function() {
var myLatLng = new google.maps.LatLng(24.86802, 67.06416);
MYMAP.init('#map', myLatLng, 11);
$(document).ready(function(e){
MYMAP.placeMarkers('testasp.asp');
});
});
var curr_infw;
var MYMAP = {
map: null,
bounds: null,
infowindow:null
}
MYMAP.init = function(selector, latLng, zoom) {
var myOptions = {
zoom:zoom,
center: latLng,
mapTypeId: google.maps.MapTypeId.HYBRID
}
this.map = new google.maps.Map($(selector)[0], myOptions);
this.bounds = new google.maps.LatLngBounds();
}
MYMAP.placeMarkers = function(filename) {
$.get(filename, function(xml){
$(xml).find("marker").each(function(){
var name = $(this).find('name').text();
var address = $(this).find('address').text();
// create a new LatLng point for the marker
var lat = $(this).find('lat').text();
var lng = $(this).find('lng').text();
var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
var infowindow = null;
// extend the bounds to include the new point
MYMAP.bounds.extend(point);
var marker = new google.maps.Marker({
position: point,
map: MYMAP.map,
clickable: true,
icon: 'truck_green.png'
});
//var infowindow = null;
infoWindow = new google.maps.InfoWindow();
var html='<strong>'+name+'</strong.><br />'+address;
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(html);
infoWindow.open(MYMAP.map, marker);
});
MYMAP.map.fitBounds(MYMAP.bounds);
});
});
}
If somebody help me out I want to refresh it using click event or settimeout function though.
Regards and looking forward to hear it here soon. thanks
Not an answer, but what's this meant to be?
$(document).ready(function() {
var myLatLng = new google.maps.LatLng(24.86802, 67.06416);
MYMAP.init('#map', myLatLng, 11);
$(document).ready(function(e){
MYMAP.placeMarkers('testasp.asp');
});
});
Why are you nesting document.ready? Just do
$(document).ready(function() {
var myLatLng = new google.maps.LatLng(24.86802, 67.06416);
MYMAP.init('#map', myLatLng, 11);
MYMAP.placeMarkers('testasp.asp');
});
For event use
google.maps.event.addListener([ mapObject ], 'bounds_changed', function() {
// [ update code here ]
});

Resources