I want remove a view before creating a new one. But my requirement is view.remove() should remove the view but not delete the el element. Having said this, I do not want to set tagName as it crates a new element which is unnecessary. Is there any way to remove a view from the memory leaving the el content cleared?
mardi 4 août 2015
How do I prevent backbone remove() from removing "el" in a view?
Why does asm.js deteriorate performance?
Just to see how it performs, I wrote a very short asm.js module by hand, which simulates the 2D wave equation using 32-bit integer math and typed arrays (Int32Array). I have three versions of it, all as similar as possible:
- Ordinary (i.e. legible, albeit C-style) JavaScript
- Same as 1, with asm.js annotations added so that it passes the validator, according to Firefox and other tools
- Same as 2, except with no "use asm"; directive at the top
I left a demo at http://ift.tt/1M8UwwH which lets you switch between modules to see the effects of using each one. All three work, but at different speeds. This is the hotspot (with asm.js annotations):
for (i = 0; ~~i < ~~h; i = (1 + i)|0) {
for (j = 0; ~~j < ~~w; j = (1 + j)|0) {
if (~~i == 0) {
index = (1 + index) | 0;
continue;
}
if (~~(i + 1) == ~~h) {
index = (1 + index) | 0;
continue;
}
if (~~j == 0) {
index = (1 + index) | 0;
continue;
}
if (~~(j + 1) == ~~w) {
index = (1 + index) | 0;
continue;
}
uCen = signedHeap [((u0_offset + index) << 2) >> 2] | 0;
uNorth = signedHeap[((u0_offset + index - w) << 2) >> 2] | 0;
uSouth = signedHeap[((u0_offset + index + w) << 2) >> 2] | 0;
uWest = signedHeap [((u0_offset + index - 1) << 2) >> 2] | 0;
uEast = signedHeap [((u0_offset + index + 1) << 2) >> 2] | 0;
uxx = (((uWest + uEast) >> 1) - uCen) | 0;
uyy = (((uNorth + uSouth) >> 1) - uCen) | 0;
vel = signedHeap[((vel_offset + index) << 2) >> 2] | 0;
vel = vel + (uxx >> 1) | 0;
vel = applyCap(vel) | 0;
vel = vel + (uyy >> 1) | 0;
vel = applyCap(vel) | 0;
force = signedHeap[((force_offset + index) << 2) >> 2] | 0;
signedHeap[((u1_offset + index) << 2) >> 2] = applyCap(((applyCap((uCen + vel) | 0) | 0) + force) | 0) | 0;
force = force - (force >> forceDampingBitShift) | 0;
signedHeap[((force_offset + index) << 2) >> 2] = force;
vel = vel - (vel >> velocityDampingBitShift) | 0;
signedHeap[((vel_offset + index) << 2) >> 2] = vel;
index = (index + 1)|0;
}
}
The "ordinary JavaScript" version is structured as above, but without the bitwise operators that asm.js requires (e.g. "x|0", "~~x", "arr[(x<<2)>>2]", etc.)
These are the results for all three modules on my machine, using Firefox (Developer Edition v. 41) and Chrome (version 44), in milliseconds per iteration:
- FIREFOX (version 41): 20 ms, 35 ms, 60 ms.
- CHROME (version 44): 25 ms, 150 ms, 75 ms.
So ordinary JavaScript wins in both browsers. The presence of asm.js-required annotations deteriorates performance by a factor of 3 in both. Furthermore, the presence of the "use asm"; directive has an obvious effect- it helps Firefox a bit, and brings Chrome to its knees!
It seems strange that merely adding bitwise operators should introduce a threefold performance degradation that can't be overcome by telling the browser to use asm.js. Also, why does telling the browser to use asm.js only help marginally in Firefox, and completely backfire in Chrome?
d3 function(d) return value from object not from the first index(0)
why d3 function(d) return value from object not from the first index(0)
tr.append('td').html(function(m) { console.log(m.INDEX) ;return m.INDEX; })
from this function i have value from index 1 to m.INDEX.length ?
Can't understand a javascript .call() usage
I'm trying to learn the three.js library by reading the "WebGL Up And Running" book and the problem for me is that the author made his own javascript framework called 'sim.js' which is a "higher-level set of reusable objects build upon three.js that wraps the more repetitive Three.js tasks" as he said but for a beginner like me i'd prefer more experiencing the raw three.js first.. So now i have to understand what his framwork does to understand what happens under the hood.
this is the sim.js
// Sim.js - A Simple Simulator for WebGL (based on Three.js)
Sim = {};
// Sim.Publisher - base class for event publishers
Sim.Publisher = function() {
this.messageTypes = {};
}
Sim.Publisher.prototype.subscribe = function(message, subscriber, callback) {
var subscribers = this.messageTypes[message];
if (subscribers)
{
if (this.findSubscriber(subscribers, subscriber) != -1)
{
return;
}
}
else
{
subscribers = [];
this.messageTypes[message] = subscribers;
}
subscribers.push({ subscriber : subscriber, callback : callback });
}
Sim.Publisher.prototype.unsubscribe = function(message, subscriber, callback) {
if (subscriber)
{
var subscribers = this.messageTypes[message];
if (subscribers)
{
var i = this.findSubscriber(subscribers, subscriber, callback);
if (i != -1)
{
this.messageTypes[message].splice(i, 1);
}
}
}
else
{
delete this.messageTypes[message];
}
}
Sim.Publisher.prototype.publish = function(message) {
var subscribers = this.messageTypes[message];
if (subscribers)
{
for (var i = 0; i < subscribers.length; i++)
{
var args = [];
for (var j = 0; j < arguments.length - 1; j++)
{
args.push(arguments[j + 1]);
}
subscribers[i].callback.apply(subscribers[i].subscriber, args);
}
}
}
Sim.Publisher.prototype.findSubscriber = function (subscribers, subscriber) {
for (var i = 0; i < subscribers.length; i++)
{
if (subscribers[i] == subscriber)
{
return i;
}
}
return -1;
}
// Sim.App - application class (singleton)
Sim.App = function()
{
Sim.Publisher.call(this);
this.renderer = null;
this.scene = null;
this.camera = null;
this.objects = [];
}
Sim.App.prototype = new Sim.Publisher;
Sim.App.prototype.init = function(param)
{
param = param || {};
var container = param.container;
var canvas = param.canvas;
// Create the Three.js renderer, add it to our div
var renderer = new THREE.WebGLRenderer( { antialias: true, canvas: canvas } );
renderer.setSize(container.offsetWidth, container.offsetHeight);
container.appendChild( renderer.domElement );
// Create a new Three.js scene
var scene = new THREE.Scene();
scene.add( new THREE.AmbientLight( 0x505050 ) );
scene.data = this;
// Put in a camera at a good default location
camera = new THREE.PerspectiveCamera( 45, container.offsetWidth / container.offsetHeight, 1, 10000 );
camera.position.set( 0, 0, 3.3333 );
scene.add(camera);
// Create a root object to contain all other scene objects
var root = new THREE.Object3D();
scene.add(root);
// Create a projector to handle picking
var projector = new THREE.Projector();
// Save away a few things
this.container = container;
this.renderer = renderer;
this.scene = scene;
this.camera = camera;
this.projector = projector;
this.root = root;
// Set up event handlers
this.initMouse();
this.initKeyboard();
this.addDomHandlers();
}
//Core run loop
Sim.App.prototype.run = function()
{
this.update();
this.renderer.render( this.scene, this.camera );
var that = this;
requestAnimationFrame(function() { that.run(); });
}
// Update method - called once per tick
Sim.App.prototype.update = function()
{
var i, len;
len = this.objects.length;
for (i = 0; i < len; i++)
{
this.objects[i].update();
}
}
// Add/remove objects
Sim.App.prototype.addObject = function(obj)
{
this.objects.push(obj);
// If this is a renderable object, add it to the root scene
if (obj.object3D)
{
this.root.add(obj.object3D);
}
}
Sim.App.prototype.removeObject = function(obj)
{
var index = this.objects.indexOf(obj);
if (index != -1)
{
this.objects.splice(index, 1);
// If this is a renderable object, remove it from the root scene
if (obj.object3D)
{
this.root.remove(obj.object3D);
}
}
}
// Event handling
Sim.App.prototype.initMouse = function()
{
var dom = this.renderer.domElement;
var that = this;
dom.addEventListener( 'mousemove',
function(e) { that.onDocumentMouseMove(e); }, false );
dom.addEventListener( 'mousedown',
function(e) { that.onDocumentMouseDown(e); }, false );
dom.addEventListener( 'mouseup',
function(e) { that.onDocumentMouseUp(e); }, false );
$(dom).mousewheel(
function(e, delta) {
that.onDocumentMouseScroll(e, delta);
}
);
this.overObject = null;
this.clickedObject = null;
}
Sim.App.prototype.initKeyboard = function()
{
var dom = this.renderer.domElement;
var that = this;
dom.addEventListener( 'keydown',
function(e) { that.onKeyDown(e); }, false );
dom.addEventListener( 'keyup',
function(e) { that.onKeyUp(e); }, false );
dom.addEventListener( 'keypress',
function(e) { that.onKeyPress(e); }, false );
// so it can take focus
dom.setAttribute("tabindex", 1);
dom.style.outline='none';
}
Sim.App.prototype.addDomHandlers = function()
{
var that = this;
window.addEventListener( 'resize', function(event) { that.onWindowResize(event); }, false );
}
Sim.App.prototype.onDocumentMouseMove = function(event)
{
event.preventDefault();
if (this.clickedObject && this.clickedObject.handleMouseMove)
{
var hitpoint = null, hitnormal = null;
var intersected = this.objectFromMouse(event.pageX, event.pageY);
if (intersected.object == this.clickedObject)
{
hitpoint = intersected.point;
hitnormal = intersected.normal;
}
this.clickedObject.handleMouseMove(event.pageX, event.pageY, hitpoint, hitnormal);
}
else
{
var handled = false;
var oldObj = this.overObject;
var intersected = this.objectFromMouse(event.pageX, event.pageY);
this.overObject = intersected.object;
if (this.overObject != oldObj)
{
if (oldObj)
{
this.container.style.cursor = 'auto';
if (oldObj.handleMouseOut)
{
oldObj.handleMouseOut(event.pageX, event.pageY);
}
}
if (this.overObject)
{
if (this.overObject.overCursor)
{
this.container.style.cursor = this.overObject.overCursor;
}
if (this.overObject.handleMouseOver)
{
this.overObject.handleMouseOver(event.pageX, event.pageY);
}
}
handled = true;
}
if (!handled && this.handleMouseMove)
{
this.handleMouseMove(event.pageX, event.pageY);
}
}
}
Sim.App.prototype.onDocumentMouseDown = function(event)
{
event.preventDefault();
var handled = false;
var intersected = this.objectFromMouse(event.pageX, event.pageY);
if (intersected.object)
{
if (intersected.object.handleMouseDown)
{
intersected.object.handleMouseDown(event.pageX, event.pageY, intersected.point, intersected.normal);
this.clickedObject = intersected.object;
handled = true;
}
}
if (!handled && this.handleMouseDown)
{
this.handleMouseDown(event.pageX, event.pageY);
}
}
Sim.App.prototype.onDocumentMouseUp = function(event)
{
event.preventDefault();
var handled = false;
var intersected = this.objectFromMouse(event.pageX, event.pageY);
if (intersected.object)
{
if (intersected.object.handleMouseUp)
{
intersected.object.handleMouseUp(event.pageX, event.pageY, intersected.point, intersected.normal);
handled = true;
}
}
if (!handled && this.handleMouseUp)
{
this.handleMouseUp(event.pageX, event.pageY);
}
this.clickedObject = null;
}
Sim.App.prototype.onDocumentMouseScroll = function(event, delta)
{
event.preventDefault();
if (this.handleMouseScroll)
{
this.handleMouseScroll(delta);
}
}
Sim.App.prototype.objectFromMouse = function(pagex, pagey)
{
// Translate page coords to element coords
var offset = $(this.renderer.domElement).offset();
var eltx = pagex - offset.left;
var elty = pagey - offset.top;
// Translate client coords into viewport x,y
var vpx = ( eltx / this.container.offsetWidth ) * 2 - 1;
var vpy = - ( elty / this.container.offsetHeight ) * 2 + 1;
var vector = new THREE.Vector3( vpx, vpy, 0.5 );
this.projector.unprojectVector( vector, this.camera );
var ray = new THREE.Ray( this.camera.position, vector.subSelf( this.camera.position ).normalize() );
var intersects = ray.intersectScene( this.scene );
if ( intersects.length > 0 ) {
var i = 0;
while(!intersects[i].object.visible)
{
i++;
}
var intersected = intersects[i];
var mat = new THREE.Matrix4().getInverse(intersected.object.matrixWorld);
var point = mat.multiplyVector3(intersected.point);
return (this.findObjectFromIntersected(intersected.object, intersected.point, intersected.face.normal));
}
else
{
return { object : null, point : null, normal : null };
}
}
Sim.App.prototype.findObjectFromIntersected = function(object, point, normal)
{
if (object.data)
{
return { object: object.data, point: point, normal: normal };
}
else if (object.parent)
{
return this.findObjectFromIntersected(object.parent, point, normal);
}
else
{
return { object : null, point : null, normal : null };
}
}
Sim.App.prototype.onKeyDown = function(event)
{
// N.B.: Chrome doesn't deliver keyPress if we don't bubble... keep an eye on this
event.preventDefault();
if (this.handleKeyDown)
{
this.handleKeyDown(event.keyCode, event.charCode);
}
}
Sim.App.prototype.onKeyUp = function(event)
{
// N.B.: Chrome doesn't deliver keyPress if we don't bubble... keep an eye on this
event.preventDefault();
if (this.handleKeyUp)
{
this.handleKeyUp(event.keyCode, event.charCode);
}
}
Sim.App.prototype.onKeyPress = function(event)
{
// N.B.: Chrome doesn't deliver keyPress if we don't bubble... keep an eye on this
event.preventDefault();
if (this.handleKeyPress)
{
this.handleKeyPress(event.keyCode, event.charCode);
}
}
Sim.App.prototype.onWindowResize = function(event) {
this.renderer.setSize(this.container.offsetWidth, this.container.offsetHeight);
this.camera.aspect = this.container.offsetWidth / this.container.offsetHeight;
this.camera.updateProjectionMatrix();
}
Sim.App.prototype.focus = function()
{
if (this.renderer && this.renderer.domElement)
{
this.renderer.domElement.focus();
}
}
// Sim.Object - base class for all objects in our simulation
Sim.Object = function()
{
Sim.Publisher.call(this);
this.object3D = null;
this.children = [];
}
Sim.Object.prototype = new Sim.Publisher;
Sim.Object.prototype.init = function()
{
}
Sim.Object.prototype.update = function()
{
this.updateChildren();
}
// setPosition - move the object to a new position
Sim.Object.prototype.setPosition = function(x, y, z)
{
if (this.object3D)
{
this.object3D.position.set(x, y, z);
}
}
//setScale - scale the object
Sim.Object.prototype.setScale = function(x, y, z)
{
if (this.object3D)
{
this.object3D.scale.set(x, y, z);
}
}
//setScale - scale the object
Sim.Object.prototype.setVisible = function(visible)
{
function setVisible(obj, visible)
{
obj.visible = visible;
var i, len = obj.children.length;
for (i = 0; i < len; i++)
{
setVisible(obj.children[i], visible);
}
}
if (this.object3D)
{
setVisible(this.object3D, visible);
}
}
// updateChildren - update all child objects
Sim.Object.prototype.update = function()
{
var i, len;
len = this.children.length;
for (i = 0; i < len; i++)
{
this.children[i].update();
}
}
Sim.Object.prototype.setObject3D = function(object3D)
{
object3D.data = this;
this.object3D = object3D;
}
//Add/remove children
Sim.Object.prototype.addChild = function(child)
{
this.children.push(child);
// If this is a renderable object, add its object3D as a child of mine
if (child.object3D)
{
this.object3D.add(child.object3D);
}
}
Sim.Object.prototype.removeChild = function(child)
{
var index = this.children.indexOf(child);
if (index != -1)
{
this.children.splice(index, 1);
// If this is a renderable object, remove its object3D as a child of mine
if (child.object3D)
{
this.object3D.remove(child.object3D);
}
}
}
// Some utility methods
Sim.Object.prototype.getScene = function()
{
var scene = null;
if (this.object3D)
{
var obj = this.object3D;
while (obj.parent)
{
obj = obj.parent;
}
scene = obj;
}
return scene;
}
Sim.Object.prototype.getApp = function()
{
var scene = this.getScene();
return scene ? scene.data : null;
}
// Some constants
/* key codes
37: left
38: up
39: right
40: down
*/
Sim.KeyCodes = {};
Sim.KeyCodes.KEY_LEFT = 37;
Sim.KeyCodes.KEY_UP = 38;
Sim.KeyCodes.KEY_RIGHT = 39;
Sim.KeyCodes.KEY_DOWN = 40;
in another script he wrote a new class called earth-basic based on the sim class so, the begining of the earth-basic.js script looks as the following :
// Constructor
EarthApp = function()
{
Sim.App.call(this);
}
// Subclass Sim.App
EarthApp.prototype = new Sim.App();
// Our custom initializer
EarthApp.prototype.init = function(param)
{
// Call superclass init code to set up scene, renderer, default camera
Sim.App.prototype.init.call(this, param);
// Create the Earth and add it to our sim
var earth = new Earth();
earth.init();
this.addObject(earth);
}
// Custom Earth class
Earth = function()
{
Sim.Object.call(this);
}
Earth.prototype = new Sim.Object();
1) what does the function call in the line "Sim.App.call(this);" written in the constructor (by passing "this" as parameter which i suppose is referring to the EarthApp variable)? all what i can guess is that EarthApp will inherit the Sim.App properties (the renderer, the camera ...). The same "technique" was used inside the "Sim.App" function itself by calling "Sim.Publisher.call(this);"
2) in 1) i supposed he just used the sim.App class as a super-Class but then all of a sudden, i found he added a new instance of sim.App() to the EarthApp's prototype by writting "EarthApp.prototype = new Sim.App();" PLease guys tell me what the heck is going on in there.
Using AJAX response in Javascript Array? [duplicate]
This question already has an answer here:
I'm not entirely sure if this is possible but I am trying to use an ajax response in a javascript array in my page.
this is what I have:
var interval = 5000;
function doAjax() {
jQuery.ajax({
type: 'POST',
url: 've.php',
dataType : 'json',
success: function (data) {
//var arr = data.split('|');
jQuery('#counterint').html(data);
var res = $.parseJSON(data);
//test: simulated ajax
var testLocs = {
<<<<<<<<<<<<<< I NEED TO USE THE "data" HERE >>>>>>>>>>>>>>>>>
};
setMarkers(testLocs);
The ajax response looks like this when I outputs it on my page in the browser:
1: { info: '1. rooz', lat: 51.5033630, lng: -0.1276250 },2: { info: '1. Rooz555', lat: 51.5033567, lng: -0.1276444 },3: { info: '1. david', lat: 51.5033777, lng: -0.1276777 },4: { info: '1. sam', lat: 51.5033555, lng: -0.1276543 },
any help would be appreciated.
Most efficient way to restructure complex array of objects in javascript?
I have a large set of data that looks similar to this:
var original = [
{ country : 'us', date : '2014-10-29', cost : 45.3 },
{ country : 'africa', date : '2014-10-29', cost : 60.5 },
{ country : 'south_america', date : '2014-10-30', cost : 10 },
{ country : 'us', date : '2014-10-30', cost : 30 }
];
I need to rearrange this data so that it looks more like this:
var newData = [
{ date : '2014-10-29', us : 45.3, africa : 60.5, south_america : 0 },
{ date : '2014-10-30', us : 30, africa : 0, south_america : 10 }
]
I'm new to dealing with datasets like this and I'm struggling to find any efficient way to handle this... The only thing I can come up with uses multiple for loops and just looks gross. Does anyone have any ideas or suggestions?
jQuery - end setinterval after X rund
I have a little slider im working on which is almost there im jsut having some trouble with me jQuery.
So first off: I want my slider to reset after the interval has run x amount of times. It was my understanding that the following would work but it doesn't seem to take. 6000, slides, function() { homesliderend();
so lets say slides = 2 set interval should call homesliderend(); but it doesn't the interval just keeps running.
Second Issue: I'm also trying to get it to add 100% to lengther every 6 seconds. But instead of adding 100 each time its just setting it to 100 its not multiplying.
jQuery(document).ready(function($) {
"use strict";
function homesliderend() {
$(".lengther").animate({
left: "0%"
}, 500);
}
function homeslider() {
var slides = $(".slide.t-align").length,
lwidth = slides * 100,
n = 0;
$(".lengther").css("width", lwidth + "%");
setInterval(function() {
var tn = n + 100;
$(".lengther").animate({
left: "-" + tn + "%"
}, 500);
}, 6000, slides, function() {
homesliderend();
});
}
homeslider();
});
how to populate select box with jquery?
i have a requirement in which when i click on a element of a list , the element gets shown as a selected option in the select box
i need to use native select box only , not to mention the elements in the list are present in the select dropdown
<button class="quick">QuickLink</button>
<div class="list">
<ul class="apps">
<li>CAPM</li>
<li>GCS</li>
<li>GRS</li>
</ul>
</div>
<select class="xyz">
<option>CAPM</option>
<option>GRS</option>
<option>BDS</option>
<option>CCAS</option>
<option>WEDAT</option>
<option>SDP</option>
</select>
jsfiddle link --> http://ift.tt/1JJS2mI
Pass ng-model as argument in directive angualjrs
I am writing a directive in angularjs and I want to pass ng-model as argument.
<div class="col-md-7"><time-picker></time-picker></div>
Directive is ,
app.directive('timePicker', function () {
return {
restrict: 'E',
replace: true,
template: '<input type="text" class="form-control time-picker" ng-model="emp.signin">',
link: function ($scope, element, form) {
$(element).timepicker({'timeFormat': 'H:i:s'});
}
}
})
It is working find, and here ng-model is emp.signin and I put this directly. I want able to pass this ng-model dynamically as argument
how it is possible?
Highcharts with DHTMLX menu appearance
I use dhtmlx menu on my charts. (legendItemClick event). It was working well when i use highcharts 3.0.1 . Today, I upgraded to 4.1.7 but dhtmlx menu's legendMenu_<?=$id?>.showContextMenu(x,y) function does not work like old one.
When i inspect the menu element on firebug, i see display: "none". I tried to change it manually. However, Id is randomly generated.
legendMenu_<?=$id?> = new dhtmlXMenuObject();
legendMenu_<?=$id?>.renderAsContextMenu();
How can i fix?
NodeJS best practices with Promises
I am developing a new library above amqp.node (amqplib), basically we dont need all the RabbitMQ functionality. So, I am creating a simple library that facilitates the usage specifically for our project.
This new library will return Promises. So, for example, subscribing to a queue will return a Promise about Ok and Error. But, what should I do with later issues? Disconnect, reconnect, Queue deleted, etc, etc? This will happen after the promise has been resolve. Should my new class emit his own errors? Is this a good way of working with promises?
How to structure Protractor promises
In this example I'm testing whether an element is located at the bottom of the page. I'm using the promises in Protractor/Webdriver, but I think I'm using it wrong because I don't think it's supposed to look this messy.
describe('Element', function(){
it('should be placed at bottom', function(){
element(by.id('page').getSize().then(function(dimP){
element(by.id('element').getLocation().then(function(locE){
element(by.id('element').getSize().then(function(dimE){
expect(locE.y + dimE.height).toEqual(dimP.height);
})
});
});
})
});
How can I do this in a cleaner way? I'm using Protractor version 2.1.0.
I have tried to do like this:
expect(element(by.id('page').getSize().height).toEqual(1000);
But it says Expected undefined to equal 1000. So it seems like I can't use return values as explained here: http://ift.tt/1sOZ9jh
(I am using a page object in my actual test, so the variables are not as ugly as in the example.)
In AngularJS how do I substitute minified javascript files with non-minified files in my development environment?
What is the best way to handle this in AngularJS?
I have an AngularJS app that includes concatenated/minified javascript files, however in my development environment I want to load the non-concatented/non-minified versions of the file. I want this because it is easier to debug the code with non-minified files.
<!-- production -->
<script src="js/all.min.js"></script> <!-- contains all concatenated/minified code -->
<!-- dev -->
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/directives.js"></script>
I am not sure how to do this since in AngularJS I couldn't find a conditional mechanism that is suitable. I had thought about using a directive on the each script tag?
I am using Gulp to concat and uglify the files, but I couldn't find a method to accomplish this with Gulp.
PHP is the server-side language.
Any help will be greatly appreciated.
How to display different pages in iframes for different time intervals dynamically
I have 2 Iframes having the ids demo and demo1. I have a list of 5 html files (promo1,promo2,promo3,promo4,promo5) which have to be displayed in both Iframes, one after the other, repeatedly. Each html page has a different time intervals for which it should be displayed in the frame
Here is my JavaScript code in which the dict represents each html and the time for which it should be displayed.
the following code makes the browser crash and fill up the memory. i know its because of the reccurrsion. please help me
;(function($){
"use strict";
var index=1,
dict={"promo1":70000,"promo2":46500,"promo3":18000,"promo4":93000,"promo5":86000},
var $firstFrame = $("#demo"),
$secondFrame = $("#demo1");
$(function (){
function demo(frameId,index){
frameId.attr("src","static/promo" + index + ".html");
frameId.load(function(){
if(a){
a.clearTimeout();
}
if(index < 5){
a = setTimeout(demo(frameId , index + 1),dict["promo"+index]);
}
else if(index = 5){
var a = setTimeout(demo(frameId , 1),dict["promo"+index]);
}
});
index += 1;
if(index > 5){
index = 1;
}
}
demo($firstFrame , 1);
});
}(window.jQuery));
Checkbox doesn't work
I have a simple code with a javascript checkbox. You can see the frontend in this website:
englishforyou.ir
When you check the check box the total price should show the new figure but it doesn't.
All my code is in one page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<div>
<div>
<?php
$title= "pen" ;
$penprice= 7 ;
?>
<form id="formpayment" action="<?php echo $urlname?>" method="post" >
<p style="color:blue; font:11px">
<input type="checkbox" id="check" name="kol" />Please add the eraser (Add 5$)
<br>
</p>
<table border="0" >
<tr>
<td><?php echo $title; ?>
</td>
<td ><input style="width: 60px; padding: 2px; border: 0px " class="txt" type="text" name="priceofpen" id="priceofpen" value="<?php echo $penprice ;?>
" readonly/> $
</td>
<td>
</td>
</TR>
<tr>
<td><?php echo "Eraser price"; ?>
</td>
<td > <input style="width: 50px; padding: 2px; border: 0px " name="priceoferaser" class="txt" id="priceoferaser" value="0" readonly="readonly" /> $
</td>
<td>
</td>
</TR>
<tr>
<td colspan="3"> <hr />
</td>
</TR>
<tr id="summation">
<td> Total:
</td>
<td>
<input style="width: 60px; padding: 2px; border: 0px " type=number name="total" id="total" value="<?php echo $penprice;?>" readonly="readonly">$
</td>
<td>
</td>
</TR>
</table>
</p><br />
</form>
</div>
</div>
<script>
$('#check').on('change',function(){
var eraserprice = "5"
var c=parseFloat(eraserprice)+ parseFloat(<?php echo $penprice;?>);
if(this.checked)
$('#total').val( c )&& $('#priceoferaser').val( parseFloat(5000) ) )
else
$('#total').val( <?php echo $penprice;?>)&& $('#priceoferaser').val( parseFloat(0) )
})
</script>
</div>
</body>
</html>
jQuery data() value conversion
I like the fact that $('element').data() converts values to integer, float, array etc.
If I use the dataset property I only get strings.
But the problem is that jQuery.data does not update the values if I alter the data attributes on the element.
Can I use dataset but also be able to convert the values like jQuery.data() does ?
For example data-num="5" should be integer, data-bool="false" should be boolean, data-arr="[1,2]" should be array etc.
Unit test nodeJS RESTful api
As its begining of my journey with unit test I have specific question about 'should that be unit tested or not'. Ive read few articles but not everything is clear for me - I guess particular decision need practice.
Situation more or less sees like this:
I have NodeJS service appplication with RESTful api. As you can guess it allows us to consume endpoints with proper headers/body/parameters.
Headers are kind of complicated - I mean, it contains authorization field and couple more. Ive figure out that I have to make a few 'worker' oraz 'factories' however we call it to provide those things.
So pseudo-code would looks like this:
DataCreator.js - is responsible for providing the whole object passed to endpoint(example below)
function PostData(schema) {
return {
data: CreatorWorker.dataForPost(someParamsToEvaluate),
headers: Headers.PostHeader(),
timeout: Config.GetTimeoutInMs();
};
}
We could use this one as:
SomeFileWithServer.js (UrlCreator is another piece of program responsible for.. of course providing proper URL)
rest.post(UrlCreator.SetPostUrl(), DataCreator.PostData())
My question is : how would unit test of DataCreator look like? What do we test here? Presence of data, headers, timeout fields? We should mock/stub all used methods (dataForPost, PostHeader...) and after that check if provided values are assign to proper fields? - or maybe both.
Going deeper.. for instance CreatorWorker.dataForPost(someParamsToEvaluate) providing body for reuqest, so inside we just check if its created in good way with proper 'someParamsToEvaluate'. --> So this situation is clear for me, one method.. it does a thing so we should check it if its done right.
So the question is, should we in such situations link particular method (e.g Headers.PostHeader) to field (headers) ? Its a good practice? Maybe we should just check if its get called? Or as I mention before we should stub it and check if headers value equals that (thats the 'linking').
Ive imagined situation when we want to refractor names of those methods, then we will have to maintain those tests.. There's plenty situations like that so I'd like to know good pattern for that.
I hope its explained clearly!
How to make a BIG stage with drag & flick inside a canvas using Pixi.js?
I am learning a PixiJS to make an animation like this: http://ift.tt/1S5a96N.
I have already created a project environment. But I am struggling with making a big stage and having a drag / flick interaction in it like the one in the website mentioned above.
How should I make a BIG stage with drag & flick inside a canvas created using PixiJS?
Here is my JavaScript code so far:
var screen_width = $(window).innerWidth();
var screen_height = $(window).innerHeight();
var renderer = PIXI.autoDetectRenderer(screen_width, screen_height, {backgroundColor: 0xcccccc});
var stage = new PIXI.Container();
var texture = new PIXI.Texture.fromImage('images/pixel.jpg');
var bg = new PIXI.Sprite(texture);
$('body').append(renderer.view);
bg.position.x = 0;
bg.position.y = 0;
stage.addChild(bg);
function animate() {
requestAnimationFrame(animate);
renderer.render(stage);
}
animate();
I do not know how to:
- draw a 1:1 size background image. This image is more than 1920x1800 in dimensions.
- implement the drag & flick interactions if the image exceeds the viewport / screen size.
Thanks. Hopefully someone will provide me with some references.
how to make use fake ui permanent in chrome?
I have made an application to record a video by following this steps : http://ift.tt/1vdZW0w,
I want access to allow the camera always 'allow', i've tried bypass the allow permission in popup allow webcam use start chrome --use--fake-ui--for--media-stream and it's work for me, but when i closed my chrome and then i opened chrome again , the popup permission allow webcam still showing, what's the solution?
How can I stop my function from returning "Reference error: (...) is not defined"
I've got this code and it's returning that reference error, but I have no idea why, I've seen lots of Q&As about reference errors, but I still can't find it. Any help is appreciated.
Thanks in advance and may the force be with you.
My code:
var data = '[{"name":"node1","id":1,"is_open":true,"children":[{"name":"node2","id":6,"children":[{"name":"child3","id":7}]},{"name":"child1","id":2}]}]';
var dadSon = [];
(function printDadSon(data, parent) {
if (!data) return;
for (var i = 0; i < (data.length); i++) {
if (parent && parent != 'undefined') {
console.log('Dad: ' + parent + ' & Son: ' + data[i].id);
dadSon += ('Dad: ' + parent + ' & Son: ' + data[i].id);
}
printDadSon(data[i].children, data[i].id);
}
})(JSON.parse(data));
printDadSon(data);
Hover effect working on most browsers, but not on safari or chrome on a MAC
In my html document, there are some tiles with two pictures (one jpg as a background and one png with transparency as a foreground) and with a hover effect: On the current tile which you are hovering, the image gets zoomed where your mouse is and the front image gets moved away from the cursor.
While moving the cursor only horizontally, all vertical pictures are animated too and the other way round.
Here is an example with all html, javascript and css:
The effect is working (with a few bugs, but that's not important).
The animations are easily added with javascript and transform3d where item is the current tile with the class .item. Variables like topRatioFron are calculated from the current mouse position relative to the current tile.
item.find('.front').css('transform', 'translate3d(0,' + topRatioFront + 'px,0)');
item.find('.back').css('transform', 'translate3d(0,' + topRatioBack + 'px,0)');
There are some variations which you can see in the jsfiddle javascript code.
The main tile gets animated with a matrix3d effect:
self.find(itemClass).css(
'transform',
'matrix3d(1,0,0.00,' + leftRatio + ',0.00,1,0.00,' + topRatio + ',0,0,1,0,0,0,0,1)'
);
In the Google Chrome Browser on Linux Mint, it works perfectly. On Google Chrome on Windows, it works too. In Mozilla Firefox, it's not as perfect as in Google Chrome, but it's okay.
The actual problem
A friend opened this site on a Mac with Safari, and all animations were really laggy (it looked like it was shaking). Another friend opened this on a Mac in the Chrome browser, and it was shaking too, but this time not in Safari.
How can I test or find out what this is causing? It can't be the performance of the computer they used, because this site with the same effect is working perfectly in ALL browsers, regardless of the operating system.
What I tried
First, I used translate instead of translate3d (I read that the latter is faster), but It didn't help.
I later added a function called requestAnimationFrame which can help rendering animations. The result was the same.
How to use Different Button in bootstrap Form
I have used Bootstrap and created form.my form Looks like
<form action="default_results.php" method="post" class="calculator" name="frmCalculator">
I have used this code in the beginning of my code and end of the page I have used three button Looks like
<div class="row">
<button id="button2" class="dont-compare shadow-inset" value="reset" >
Reset</button>
<button id="button3" data-toggle="pop" class="dont-compare shadow-inset" class="update" >
Update MI</button>
<button id="Button4" class="dont-compare shadow-inset" class="calculator" >
Calculate Scenarios</button>
</div>
I have another page its called default_ results.php page. I want to load that page when I click Calculate Scenarios button.I have used href tag for that button. But that three button also load default_results page.
How to set particular button? please any idea about it?
How to get value of a HTML tag receiving from ajax call
I am receiving below html from vbscript page by ajax call.
<html>
<body>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td width="100%" valign="top">
<div id="xyz"></div>
<input name="a1" type="hidden" value="">
<input name="a2" type="hidden" value="586546d5">
<input name="a3" type="hidden" value="13025">
<br clear="all">
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Is it possible to get value of input tag where name="a2" in ajax. // i.e we want value 586546d5 in the variable.
D3.js text element does not display unicode character correctly
I'm trying to append ➤ into SVG using unicode as seen below.
g.append("text")
.attr("x", function(d) { return x(d.value) })
.attr("y", 10)
.attr("dy", ".55em")
.attr("font-family", "FontAwesome")
.text("➤");
➤ is displayed, but not ➤
How to change the message in checkedmultiSelect widget in dojo?
Im using the dojo widget CheckedMultiSelect,how to change the message "0 items(s) selected".
var select = new CheckedMultiSelect({
dropDown: true,
labelText: 'States',
multiple: true,
name: 'state',
onChange: getValues,
required: true
}, "stateSelect");
Read value of previously assigned function to onclick event by javascript
I have this code:
document.getElementById(myid).onclick = function() {
HandleGPIO(val1, val2);
};
if (console) {
console.log(document.getElementById(myid).getAttribute('onclick'));
}
And I would like to see how function HandleGPIO() was assigned.
how to debug it? getAttribute does not work here and returns null only
Cordova PhoneGap upgrade to 5.1.1 from 2.2.0
I have Cordova application which is version 2.2.0. Now I want to upgrade, I have done upgrade part, after upgrading, application images are not display, it came blank screen. even splash screen also not came. Here is my code
Seem problem in my BaseScreen.js. I have given alert & check HomeScreen.js before execute basescreen part, the alert is working. but Basescreen also alert came,
HomeScreen.js
var HomeScreen = BaseScreen
.extend({
templateContent : "<ul id='homeBtnsList'>\
alert("-----HI-Home in---");
<li id='playGame'><img src='interface/play-icon@2x.png'><div class='gloss'></div><span>" + language.HOME_PLAY_GAME + "</span></li>\
<li id='viewScore'><img src='interface/scoreboard-icon@2x.png'><div class='gloss'></div><span>" + language.HOME_VIEW_SCORE + "</span></li>\
<li id='viewRules'><img src='interface/instruction-icon@2x.png'><div class='gloss'></div><span>" + language.HOME_VIEW_RULES + "</span></li>\
</ul>\
<div class='copyright'>Copyright © Pearson</div>\
<div class='about'></div>\
<div id='footer'>\
",
headerClass : "head homehead",
screenClass : "",
initialize : function() {
_.bindAll(this, "handleRenderComplete", "handleItemClick", "initScroll", "closeAboutUs", "aboutUsAction");
BaseScreen.prototype.initialize(this);
this.bind(AppEvent.RENDER_COMPLETE, this.handleRenderComplete);
_.extend(this, Backbone.Events);
},
render : function() {
this.element = this.el;
var divString = BaseScreen.prototype.render(this);
return divString;
},
show : function() {
this.setScreenReady();
},
handleRenderComplete : function() {
$("#homeBtnsList li", this.obj).bind(AppEvent.CLICK, this.handleItemClick);
$("div.about", this.obj).bind(AppEvent.CLICK, this.aboutUsAction);
if(isIOS()) {
ShareKitPlugin.prototype.logoutFromTwitter();
ShareKitPlugin.prototype.logoutFromFacebook();
_.delay(navigator.splashscreen.hide,1000);
}
},
setScreenReady : function() {
var obj = {
screenId : this.model.toString()
};
this.trigger(AppEvent.SCREEN_READY, obj);
},
handleItemClick : function(e) {
// alert(e.target.nodeName + " : " +
// e.target.parentNode.nodeName);
var tar = e.target;
if (e.target.nodeName.toLowerCase() != "li") {
tar = e.target.parentNode;
// return;
}
// alert(tar.nodeName + " : " + tar.parentNode.nodeName);
et = tar;
e.preventDefault();
var obj = {};
id = $(et).attr('id') ? $(et).attr('id') : $(et).find('li')
.attr('id');
switch (id) {
case "playGame":
obj.screenId = AppConst.GROUP_SCREEN;
this.trigger(AppEvent.GOTO_SCREEN, obj);
return;
case "viewScore":
obj.screenId = AppConst.SCORE_HOME_SCREEN;
this.trigger(AppEvent.GOTO_SCREEN, obj);
return;
case "viewRules":
obj.screenId = AppConst.INSTRUCTION_SCREEN;
this.trigger(AppEvent.GOTO_SCREEN, obj);
return;
default:
return;
}
;
},
initScroll: function(obj){
utils.log("SCROLL ACTIVE")
this.iScroll = new iScroll($("#helpContent").get(0), {desktopCompatibility:true});
},
aboutUsAction: function(){
var obj = {};
obj.screenId = AppConst.ABOUTUS_SCREEN;
this.trigger(AppEvent.GOTO_SCREEN, obj);
},
closeAboutUs: function(){
$("#helpWrapper #helpContent").html("");
$('#helpWrapper').hide();
this.iScroll.destroy();
},
destroy : function() {
utils.log("destroy ", this.model.get('myId'));
//$("#homeBtnsList li", this.obj).unbind();
$("div.about", this.obj).unbind();
this.unbind();
BaseScreen.prototype.destroy(this);
}
})
This is my BaseScreen.js
var BaseScreen = Backbone.View.extend
({
templateStart:"<div id='<%=myId%>' class='screen <%=screenClass%>'>\
<!--header-->\
<div id='header' class='head <%=headerClass%>'>\
<!--LEFT BTN-->\
<div class='header-left-btn <%=leftBtnClass%>'>\
<span><%=leftLabel%></span>\
</div>\
<!--TITLE-->\
<h1><%=title%></h1>\
<!--RIGHT BTN-->\
<div class='header-right-btn <%=rightBtnClass%>'>\
<%=rightLabel%>\
</div>\
</div>\
<div class='content'>",
templateContent:"",
templateClose:"</div></div>",
element:null,
render:function(extendedObject)
{
var curObj = extendedObject || this;
//console.log('screen Element: ' + curObj.el.get(0).id)
var baseScreenModel = {};
if(curObj.model){
baseScreenModel = curObj.model.toJSON();
}
var thatId = baseScreenModel.myId;
var template = _.template(curObj.templateStart + curObj.templateContent + curObj.templateClose);
var data = _.extend(baseScreenModel, {
screenClass: curObj.screenClass,
headerClass: curObj.headerClass
});
// curObj.element.append(template(baseScreenModel));
curObj.element.append(template(baseScreenModel));
// //console.log(template(baseScreenModel))
// //console.log(" >>>> " + thatId)
//var screen = curObj.element.find("#" + thatId);
var screen = $("#" + thatId);
////console.log("appended node " + screen.length);
if(screen.length <= 0){
////console.log("length is zero")
//console.log("delay .....");
_.delay(BaseScreen.prototype.render, 1000, curObj);
return curObj.element;;
}
////console.log("appended node == " + screen.html());
var sClass = curObj.screenClass || "";
var hClass = curObj.headerClass || "";
//screen.find(".screen").addClass(sClass);
//screen.find("#header").addClass(hClass);
$(screen).addClass(sClass);
$("#header", $(screen)).addClass(hClass);
// screen.find("#leftElement").bind(AppEvent.CLICK, curObj.handleButtonClick);
// screen.find("#rightElement").bind(AppEvent.CLICK, curObj.handleButtonClick);
$("#leftElement", $(screen)).bind(AppEvent.CLICK, function(e){
////console.log("#leftElement ", e.target);
that.trigger(AppEvent.HEADER_ITEM_CLICKED, AppConst.HEADER_LEFT_ELEMENT);
});
$("#rightElement", $(screen)).bind(AppEvent.CLICK, function(e){that.trigger(AppEvent.HEADER_ITEM_CLICKED, e.target.id);});
curObj.trigger(AppEvent.RENDER_COMPLETE);
return curObj.element;
},
initialize:function(extendedObject) //only called when extending BaseScreen
{
var curObj = extendedObject||this;
//_.bindAll(curObj, "handleButtonClick");
_.extend(curObj, Backbone.Events);
},
handleButtonClick:function(e)
{
this.trigger("buttonClick", e.target.id);
},
destroy:function(extendedObject) {
var that = extendedObject||this;
var thatId = that.model.get('myId');
var screen = that.element.find("#" + thatId);
screen.find("#leftElement").unbind();
screen.find("#rightElement").unbind();
//debug.log("destroy base screen for " + thatId);
screen.remove();
},
handleHeaderLeftClicked:function() {
//console.log("left clicked", this);
if(DEVICE_TYPE == DEVICE_ANDROID || DEVICE_TYPE == DEVICE_ANDROID_TAB || DEVICE_TYPE == DEVICE_PC) {
Functions.prototype.exit();
}
}
})
index.html:
<!DOCTYPE html>
<html manifest="appcache.manifest">
<head>
<meta name="apple-mobile-web-app-capable" content="yes" >
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" >
<title>My Application</title>
<link href="css/global.css" media="all" rel="stylesheet" type="text/css">
<script src="com/external/underscore.js" ></script>
<script src="com/external/iscroll.js" ></script>
<script src="com/external/zepto.js" ></script>
<script src="com/external/ajax.js" ></script>
<script src="com/external/touch.js" ></script>
<script src="com/external/event.js" ></script>
<script src="com/external/effects.js" ></script>
<script src="com/external/detect.js" ></script>
<script src="com/external/jsOAuth-1.3.1.js" ></script>
<script src="com/external/json2.js" ></script>
<script src="com/external/jsPatch.js" ></script>
<script src="com/external/backbone.js" ></script>
<script src="com/imfinity/comp/webkitdragdrop.js" ></script>
<script src="com/imfinity/utils/jsExtended.js" ></script>
<script src="com/imfinity/utils/stopwatch.js" ></script>
<script src="com/imfinity/screen/BaseScreenVO.js" ></script>
<script src="com/imfinity/screen/BaseScreen.js" ></script>
<script src="com/sns/init.js"></script>
<script src="com/sns/jsonParser.js" ></script>
<script src="com/sns/utilities.js" ></script>
<script src="com/sns/language.js" ></script>
<script src="com/sns/AppConst.js" ></script>
<script src="com/sns/services.js" ></script>
<script src="com/sns/db.js" ></script>
<script src="com/sns/AppEvent.js" ></script>
<script src="com/sns/controller/main.js" ></script>
<script src="com/sns/model/HomeScreenVO.js" ></script>
<script src="com/sns/view/HomeScreen.js" ></script>
<script src="com/sns/view/helpScreenView.js" ></script>
<script src="com/sns/model/helpScreenVO.js" ></script>
<script src="com/sns/view/aboutScreenView.js" ></script>
<script src="com/sns/model/aboutScreenVO.js" ></script>
<script src="com/sns/model/scoreHomeScreenVO.js" ></script>
<script src="com/sns/view/scoreHomeScreenView.js" ></script>
<script src="com/sns/model/hallOfFameScreenVO.js" ></script>
<script src="com/sns/view/hallOfFameScreenView.js" ></script>
<script src="com/sns/model/scoreboardScreenVO.js" ></script>
<script src="com/sns/view/scoreboardScreenView.js" ></script>
<script src="com/sns/model/instructionScreenVO.js" ></script>
<script src="com/sns/view/instructionScreenView.js" ></script>
<script src="com/sns/model/groupsScreenVO.js" ></script>
<script src="com/sns/view/groupsScreenView.js" ></script>
<script src="com/sns/model/topicsScreenVO.js" ></script>
<script src="com/sns/view/topicsScreenView.js" ></script>
<script src="com/sns/model/recentTopicsScreenVO.js" ></script>
<script src="com/sns/view/recentTopicsScreenView.js" ></script>
<script src="com/sns/view/questionScreenView.js" ></script>
<script src="com/sns/model/questionScreenVO.js" ></script>
<script src="com/sns/controller/questionPlayer.js" ></script>
<script src="com/sns/view/resultsScreenView.js" ></script>
<script src="com/sns/model/resultScreenVO.js" ></script>
<script src="com/sns/view/activity/reorderingView.js" ></script>
<script src="com/sns/view/activity/tapNplaceView.js" ></script>
<!--script src="com/sns/sns-minified.js"></script-->
</head>
<body onload="onLoad()" style="overflow: hidden;">
<div class='insOverlay'>
<div id='instructionsWrapper'><img/>
</div>
</div>
<div id="overlay">
<div id="preloader"></div>
<div id="genericHUD" >
<div id='HUDcontent'><img src='interface/load.png'>
</div>
</div>
</div>
<div id="toast" class="Overlay_toast" style="display: none;">
<div class="toast_message"></div>
</div>
<div id='helpWrapper' class="overlay darkShade" style="display: none;">
<div class="helpWindow">
<span id='helpClose' class="close-pop-up"></span>
<h1>Help</h1>
<div id='helpContent' class="helpContent"></div>
</div>
</div>
<div id="banner" class="overlay darkShade"></div>
<div class="modalOverlay" style="display: none;">
<div class="modalWindow">
<span class="close-pop-up"></span>
<h1 class="whiteHeading">Share</h1>
<p id='email' class="share-btn share-with-friend">
</p>
<p id='twitter' class="share-btn share-on-twitter">
</p>
<p id='facebook' class="share-btn share-on-facebook">
</p>
</div>
</div>
<div class="editTextOverlay">
<div class='editTextPopup'>
<div class="editTextHeader">
<span id="leftBtn" class="editTextButton">Cancel</span>
<span id="rightBtn" class="editTextButton"></span>
</div>
<textarea rows="4" autocomplete="off" spellcheck="false" style="outline: none;" maxlength="140"></textarea>
</div>
</div>
<div class="normalOverlay" id="confirmBox">
<div class='normalTextPopup'>
<h2>Confirm</h2>
<div id="confirmMsg">
message
</div>
<div>
<span id="leftBtn" class="normalTextButton"></span>
<span id="rightBtn" class="normalTextButton"></span>
</div>
</div>
</div>
<div id="wrap" >
<div id="screens" >
<div id='questionPlayer' class='screen'></div>
</div>
</div>
</body>
</html>
cofig : res/xml/config.xml
<?xml version='1.0' encoding='utf-8'?>
<cordova>
<access origin="http://127.0.0.1*" />
<access origin=".*" />
<log level="DEBUG" />
<preference name="useBrowserHistory" value="true" />
<preference name="exit-on-suspend" value="false" />
<preference name="SplashScreen" value="splash" />
<preference name="SplashScreenDelay" value="10000" />
<preference name="SplashMaintainAspectRatio" value="true" />
<plugins>
<plugin name="App" value="org.apache.cordova.App" />
<plugin name="Geolocation" value="org.apache.cordova.GeoBroker" />
<plugin name="Device" value="org.apache.cordova.Device" />
<plugin name="Accelerometer" value="org.apache.cordova.AccelListener" />
<plugin name="Compass" value="org.apache.cordova.CompassListener" />
<plugin name="Media" value="org.apache.cordova.AudioHandler" />
<plugin name="Camera" value="org.apache.cordova.CameraLauncher" />
<plugin name="Contacts" value="org.apache.cordova.ContactManager" />
<plugin name="File" value="org.apache.cordova.FileUtils" />
<plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager" />
<plugin name="Notification" value="org.apache.cordova.Notification" />
<plugin name="Storage" value="org.apache.cordova.Storage" />
<plugin name="FileTransfer" value="org.apache.cordova.FileTransfer" />
<plugin name="Capture" value="org.apache.cordova.Capture" />
<plugin name="Battery" value="org.apache.cordova.BatteryListener" />
<plugin name="SplashScreen" value="org.apache.cordova.SplashScreen" />
<plugin name="Echo" value="org.apache.cordova.Echo" />
<plugin name="Globalization" value="org.apache.cordova.Globalization" />
<plugin name="SQLitePlugin" value="com.phonegap.plugins.SQLitePlugin" />
<plugin name="FlurryPlugin" value="com.phonegap.plugins.Flurry" />
<plugin name="AndroidUtilsPlugin" value="com.phonegap.plugins.AndroidUtilsPlugin" />
<plugin name="ChildBrowserPlugin" value="com.phonegap.plugins.ChildBrowserPlugin" />
</plugins>
<feature name="File">
<param name="android-package" value="org.apache.cordova.file.FileUtils" />
<param name="onload" value="true" />
</feature>
</cordova>
Please let me know what is an issue. After upgrading only , I am facing this isssue, could you please guide me about this.
How to change Images with JavaScript?
I got a acordeon that works and only one at a time can be open. The arrow starts with down but if you click it, the icon changes to up. Now i tryed to make it with images because i dont like the possible icons. The thing is my JavaScript worked for icons but after trying I dont get how to use it with images.
Here my JavaScript
jQuery(document).ready(function () {
$(".flip").click(function () {
/*Alle anderen werden geschlossen und auf circle-down gestellt wärend der eigene circle-up gestellt wird oder falls er schon up ist auf circle-down.*/
$(".panel").not($(this).next(".panel").slideToggle("slow")).slideUp("slow");
if($("i",this).hasClass('fa-chevron-circle-down')){
$(".fa-chevron-circle-up").removeClass("fa-chevron-circle-up").addClass("fa-chevron-circle-down");
$("i",this).removeClass("fa-chevron-circle-down").addClass("fa-chevron-circle-up");
}
else{
$("i",this).removeClass("fa-chevron-circle-up").addClass("fa-chevron-circle-down");
}
});
});
and the HTML
<div class="flip shadow-box col-xs-12 col-md-12 col-sm-12 arrow-icon-geschaeftsfelder">
<i class="fa fa-chevron-circle-down"></i>
</div>
If anybody tried the same thing allready, any help would be great :D
how to switch driver control from the top window to iframe#mainFrame
I am using firebug to inspect the xpath, one block of firebug shows the element your finding is in window or iframe and so on. I am facing similar kind of problem where it shows me 2 options 1: Top window 2: iframe#mainframe now the problem is,when i inspect the element it shows in iframe#mainFrame, i tried switching the driver control from main window to iframe and detect the element using webdriver but it didn't work for me,I wrote the following set of code:
driver.switchTo().frame("mainFrame");
driver.findElement(By.xpath("//div[@class='div_img']/img[@src='http://ser/themes/20/3/Flor/CF.jpg']")).click();
Note: when i checked the iframe in the html code,it doesn't contain another document inside it, It only contains id and other style and all and src tag.
Kindly suggest if there is some other way through which i can detect the element.
Access from change event to other input html jquery autocreate
My problem is:
I have a page with a table is auto generated with ajax-jquery
My table is 3 1: name 2-3: checkbox for parameters
I set event on all input:checkbox ("change") event.
The problem appears when i try to get check state of checkbox different than i click.
code:
$(document).ready(function() {
$("#permessiAttributiDiv").on("change", "input:checkbox", function() {
var IDPermesso = $(this).attr("id").substring(1);
var selezionatoSpuntato = (this.checked);
var altro = $(this).parent().find("input:checkbox").checked;
var scheda = $("#selectTipo").val();
});
)};
I also try to get check state by id but i always doesn't work......
I see if the checkbox is write in html static code all works ok but if i generate it with jquery i can't access to input with any selector.....
Can anyone help me?
Thanks
How to split jquery source code into multiple files when using the module pattern?
I've got some problems splitting up my jquery source code into more than one file. My real source code is a bit more complicated but the following simple example shows my problem very good. At first I would like to show you a working example with only one javascript file. Afterwards, I will describe what I tried in order to split the javascript into two files.
My html code looks like this ("./jquery" is a symbolic link to my local jquery download):
<html>
<head>
<script src="./jquery"></script>
<script src="./file1.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
The jquery source code in file1.js looks like this:
$(document).ready(function() {
var Test = (function() {
var content = $('#content');
var init = function() {
content.html('<p>test</p>');
};
return {
init: init
}
})();
Test.init();
});
After opening the page, "test" is displayed so that this example works as expected.
But now I want to put the whole Test part into another file file2.js. My html is basically the same but gets an additional line:
<script src="./file2.js"></script>
file1.js now contains only the call of the init function:
$(document).ready(function() {
Test.init();
});
and file2.js contains the definition of Test:
var Test = (function() {
var content = $('#content');
var init = function() {
content.html('<p>test</p>');
};
return {
init: init
}
})();
When I open the page, "test" is not displayed any more. In order to make sure that the init function is called at all, I added a console.log("test"); to the init function which is working fine. Therefore, I suppose that the function might be called before the DOM is ready, but actually I am pretty clueless. Maybe someone can give me a hint how to make that run.
Best regards and thanks in advance!
Display text given a counters current count
At present I have a very basic Javascript counter-style function:
<body>
<script type="text/javascript">
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onClick="onClick()">Add One To Chain</button>
<p>Chain: <a id="clicks">0</a></p>
</body>
However now I wish to present the user with different text prompts at different points whilst counting.
For example if the counter reaches 10 I would like it to say hello, and if it reaches 20 it would say something like keep going, and at 30 STOP! and so on.
Any help would be much appreciated!
Best way to combine Python (backend) and d3.js to create a real-time data visualisation [on hold]
I am looking for is the best way to combine Python (backend) and d3.js to create a real-time data visualisation
I have coded a tool in Python that produces data about a network and updates the information potentially in real-time. I would like to show the development of the network in real-time in the browser. There will be a few thousand nodes.
The Python tool produces a Pandas dataframe like this (I am not sure where the aggregation step should take place though):
The output should be a (real-time interactive) network like this:
How do I "connect" Python with d3.js so that the graph can be visualised in (near) real-time?
Even hints would be very much appreciated.
EXTJS: How can i upgrade my Sencha EXTJS 5.0.1 application to EXTJS 5.1.1 version?
I want to upgrade my current application which was built in EXTJS 5.0.1 version with Sencha CMD 5.0.1 . Can somebody please provide the exact steps needed to upgrade it to Sencha EXTJS 5.1.1 version ?
Thanks!
How to add ngAnimate to the UL and LI which is generated using ngRepeat?
I am working on animating ui->li which is generated using ngRepeat
I a working example in jquery here :
<div class="accordion-wrapper">
<ul class="accordion-root">
<li class="accordion-key">
<div class="accordion-group-header">item 1</div>
<ul class="accordion-group">
<li class="accordion-key">
<div class="accordion-group-header">sub item 1</div>
<ul class="accordion-group">
<li>tertiary item 1</li>
<li>tertiary item 2</li>
<li>tertiary item 3</li>
<li>tertiary item 4</li>
<li>tertiary item 5</li>
<li>tertiary item 6</li>
</ul>
</li>
<li>sub item 2</li>
<li>sub item 3</li>
<li>sub item 4</li>
<li>sub item 5</li>
</ul>
</li>
<li>item 2</li>
<li>item 3</li>
</ul>
</div>
<script src="http://ift.tt/1Gufy1b"></script>
<script type="text/javascript">
$(function() {
// initialize accordion by hiding all branches
$('.accordion-wrapper .accordion-group').hide()
/* ** Work-around for <UL> and <LI> elements not having full-width hit-areas for hover and click actions **
wrap all text items inside accordion with highlight and backlight to enable full-width item selection
.highlight is placed above the text item in the DOM and .backlight is placed below the text item
.highlight accepts all hover and click actions and turns the item's .backlight ON or OFF. */
$('.accordion-wrapper li:not(.accordion-key), .accordion-group-header')
.prepend('<div class="accordion-item-highlight"></div>')
.append('<div class="accordion-item-backlight"></div>')
/* item DOM:
<li>
<div class="accordion-item-highlight"></div>
item text
<div class="accordion-item-backlight"></div>
</li> */
$('.accordion-group-header .accordion-item-highlight').on('click', function(e) {
if(this == e.target) {
$(this).closest('.accordion-key').children('.accordion-group').toggle('fast')
}
})
})
</script>
And I am trying to do same using angular js
angular example is here which is not working:
<accordion-group group=tree domains=nets.data.domains></accordion-group>
<script src="http://ift.tt/1KZVmfn"></script>
<script type="text/javascript">
angular.module('accordion', ['ngAnimate'])
.controller('main', ['$scope', function($scope){
$scope.nets = {
"data": {
"symbols": {},
"domains": {
"Root": [
"GR_5",
"SIM069081008:Root",
"SIM069081001:Root",
"SIM069081012:Root"
],
"GR_5": [
"SIM069081001:GR_5",
"SIM069081004:GR_5"
],
"MyNetwork": ["Root"]
},
homeGroup: "MyNetwork"
}
}
var treeRootName = $scope.nets.data.domains[$scope.nets.data.homeGroup][0]
$scope.tree = $scope.nets.data.domains[treeRootName]
// if array item is a node, print it out using template else build out it's children into the next layer by passing $scope.domains.<domain-name> as the source for the next level of accordion-group
}])
.directive('accordionGroup', function() {
return {
restrict: 'E',
replace: true,
scope: { group: '=', domains: '=' },
template: ' <ul class="repeat" ng-class="repeat" ng-animate="{enter: \'repeat-enter\',leave: \'repeat-leave\',move: \'repeat-move\'}"> \
<accordion-key class="accordion-key" ng-repeat="key in group" key=key domains=domains ng-click="toggle($event, key)"></accordion-key> \
</ul>',
link: function(scope, element, attrs) {
scope.group = scope.group.map(function(key) {return {name: key} })
angular.forEach(scope.group, function(key) {
if(key.name.indexOf('SIM') == -1) {
console.log('setting collapse', key)
key.collapsed = true
console.log('collapse set complete', key)
}
})
scope.toggle = function($event, key) {
$event.stopPropagation()
key.collapsed = !key.collapsed
}
}
}
})
.directive('accordionKey', function($compile, $rootScope) {
return {
restrict: 'E',
replace: true,
scope: {key: '=', domains: '='},
template: '<li >{{key.name}}</li>',
link: function(scope, element, attrs) {
if(scope.key.name.indexOf('SIM') == -1) {
// console.log(scope.key.name, scope.key.collapsed)
$compile('<accordion-group class="accordion-group" group=domains[key.name] domains=domains ng-show=!key.collapsed></accordion-group>')(scope, function(cloned, scope) {
element.append(cloned)
})
}
}
}
})
</script>
code plnkr
I am not able to apply ngAnimate for UL/LI
Kendo grid json post
I have an MVC application using a Kendo grid as follows:
var products = [{
ProductID: 1,
FullName: "Chai",
IsHeadmaster: "T"
}];
$("#teachers").kendoGrid({
dataSource: {
type: "json",
transport: {
read: function (e) {
// on success
e.success(products);
// on failure
//e.error("XHR response", "status code", "error message");
},
update: {
type: "POST",
url: "/Home/UpdateTeachers",
dataType: "json",
contentType: "application/json"
},
parameterMap: function(data, operation) {
if (operation === "update" || operation === "create") {
return JSON.stringify({product: data});
}
return data;
}
},
batch: true,
schema: {
model: {
id: "TeacherId",
fields: {
TeacherId: { type: "number" },
FullName: { type: "string" },
IsHeadmaster: { type: "boolean" }
}
}
}
},
toolbar: ["create", "save"],
columns: [
{ field: "FullName", title: "Teacher" },
{ field: "IsHeadmaster", title: "Is a Headmaster?", width: "120px" },
{ command: ["destroy"], title: " ", width: "85px" }],
editable: true
});
And my controller as:
public JsonResult UpdateTeachers(string models)
{
// do update here
}
The grid loads and displays perfectly, however when i try to make an edit and update i get the following error:
Unhandled exception at line 6684, column 17 in http://localhost:5227/kendo/js/kendo.web.js
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'call'
I'm using JQuery 1.8.2.
Any ideas/help would be greatly appreciated?
ExtJS 4.0.7 function handler in button
How do I write a function handler in "button" which is present in the below code so that when we click on that button after providing the "channel url" it will go to that particular "channel url view source" and retrieve "channel name and channel id" from that "channel url view source" and display it in the "channel name and channel id textfield".
[
{
formitems:[
{
xtype:'dsqfieldcontainer',
layout:{
type:'hbox'
},
items:[
{
mapping:'ChannelURL',
name:'ChannelURL',
fieldLabel:'Channel URL',
xtype:'dsqtextfield'
},
{
name:'Look_Up_ChannelID',
xtype:'dsqbutton',
text:'Button Name'
}
]
},
{
mapping:'CHANNELNAME',
name:'CHANNELNAME',
fieldLabel:'Channel Name',
xtype:'dsqtextfield'
},
{
mapping:'CHANNELID',
name:'CHANNELID',
fieldLabel:'Channel ID',
xtype:'dsqtextfield'
},
{
mapping:'REFRESHTOKEN',
name:'REFRESHTOKEN',
fieldLabel:'Refresh Token',
xtype:'dsqtextfield'
}
]
}
]
This is the link where my code is available http://ift.tt/1P3ickx
Executing iOS Instruments Javascript code via Appium
I want to execute iOS Instruments UIAutomation javascript code using Appium. I am aware that I can execute some javascript from Appium using the following methods:
apmDriver.execute(driverCommand, parameters);
apmDriver.executeAsyncScript(script, args);
apmDriver.executeScript(script, args);
Suppose if I directly want to interact with Instruments UIAutomation by passing instruments javascript code. For example:
apmDriver.executeScript("var target = UIATarget.localTarget();
var appWindow = target.frontMostApp().mainWindow();
appWindow.tabBar().buttons()[\"Unit Conversion\"].tap()",null)
Is it possible to do this on an iOS native app?
JavaScript: Check / Compare values of all fields
In my JavaScript function I give all input-, textarea- and select-fields the actual value as an initial_value:
$('input, textarea, select').each(function (i) {
$(this).data('initial_value', $(this).val());
});
So I can check by keyup if there are any changes in a field:
$("body").on("keyup", 'input, textarea, select', function() {
if ($(this).val() != $(this).data('initial_value')) {
handleFormChanged();
changeMessage();
}
});
But also I want to check by keyup if the changes were deleted out of the fields. My idea was to check with an else if if the value in all fields is equal to the initial_value in all fields. It is important to know if really the value in ALL fields is equal to the initial_value. But it doesn´t work. Any better ideas? Thanks a lot!
ExtJS 4 menu position
I'm new to ExtJS so please don't throw a thunderstorm of downvotes right away. I've looked in documentation and tried few possible solutions, but nothing works. I need to change the default behavior of menus. I have a button that triggers a menu dropdown and it works all fine until the browser window is too small to show entire dropdown, in which case it 'undocks' and ExtJS is trying to fit it in the window. I need it to stay where it is, relative to the button that triggered it. How can I do this in ExtJS? Thanks.
How to send image as ajax parameter
I need to save object HTMLImageElement in excel file. I am using highchart and get the image of the chart by getSVG method (Overall process in [http://ift.tt/1JJRGwy])
Now i am trying to write this image into excel file. for doing that i need to pass the image by webservice but i am stuck into overall process. what i have tried is the following:
var svg = chart.getSVG({
exporting: {
sourceWidth: chart.chartWidth,
sourceHeight: chart.chartHeight
}
});
var canvas = document.createElement('canvas');
canvas.height = render_height;
canvas.width = render_width;
var image = new Image;
image.onload = function () {
canvas.getContext('2d').drawImage(this, 0, 0, render_width, render_height);
var data = canvas.toDataURL("image/png")
download(data, filename + '.png');
};
var dataitem= JSON.stringify({ data: image});
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
datatype: "json",
data: dataitem,
url: "FrontDesign/Sendimage",
success: function (data) {
//code for success
}
});
I know JSON.stringify({ data: image}) is not process to pass. Any Suggestion regarding this matter?
rails upload file from local database to S3
Hi i have rails app in that i stored all files in database when i click on upload button then that file must upload on s3 and stored file reference in database Currently i am use following way but its not working not getting file object
<% @documents.each do |fileData| %>
<tr>
<td><%= fileData.filename %></td>
<td><%= link_to 'Upload file', '#', :onclick => "getFile(#{fileData.id})" %></td>
<td><%= button_to 'Destroy', fileData, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
so how to send file object in javaScript function :onclick => getFile(fileObject)
Redirect with javascript "&" in url
I am trying to use JavaScript for redirecting to affiliate links. The problem is that the url contains & which changes to & after the redirect.
location.href ="http://ift.tt/1DmTnyQ"
will in the web browser be changed to
http://ift.tt/1IDqgD4
With & in the url the affiliate link doesn't work.
How can I fix this problem? encodeURIComponent()?
Send numbers from php to js in separated files
How to send variables from php to js in separated files. Can I make this without ajax or I need ajax for this. If I need ajax how to make with ajax.
test.php
<?php
$a = 5;
$b = 10;
?>
test.js
var sum =<?php echo $a?> + <?php echo $b?>
document.write(sum);
Angular Protractor tests fail with Select2 inside Modal
I’m trying to run my angular e2e tests with protractor. I’ve got some situations where a select exists inside a modal. Depending on the machine running the tests, this sometimes fails as protractor can’t find the select with:
NoSuchElementError: No element found using locator: By.cssSelector("div#s2id_items”)
On a slower machine this works every time, while on faster machines it often fails. My guess is that the modal is still being animated when protractor tries to access the selector, hence, resulting in failure.
I’ve tried to disable animations without success with the code bellow inside the onPrepare directive in my protractor config:
var disableNgAnimate = function() {
angular.module('disableNgAnimate', []).run(['$animate', function($animate) {
$animate.enabled(false);
}]);
};
browser.addMockModule('disableNgAnimate',disableNgAnimate);
I’m using angular 1.4.3 with bootstrap 3.3.5 and protractor 2.1.0.
Thanks
Edit:
1 - I'm not using explicit waits and I wouldn't like to, as these would either considerably slow down tests or still be prone to failure in some scenarios.
d3 heatmap box should create on boolean value
i want to build a heatmap based on boolean value array like :
and result should be :
I have found this :
var margin = { top: 50, right: 0, bottom: 100, left: 30 },
width = 960 - margin.left - margin.right,
height = 430 - margin.top - margin.bottom,
gridSize = Math.floor(width / 24),
legendElementWidth = gridSize*2,
buckets = 9,
colors = ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"], // alternatively colorbrewer.YlGnBu[9]
days = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
times = ["1a", "2a", "3a", "4a", "5a", "6a", "7a", "8a", "9a", "10a", "11a", "12a", "1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p", "10p", "11p", "12p"];
d3.tsv("data.tsv",
function(d) {
return {
day: +d.day,
hour: +d.hour,
value: +d.value
};
},
function(error, data) {
var colorScale = d3.scale.quantile()
.domain([0, buckets - 1, d3.max(data, function (d) { return d.value; })])
.range(colors);
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var dayLabels = svg.selectAll(".dayLabel")
.data(days)
.enter().append("text")
.text(function (d) { return d; })
.attr("x", 0)
.attr("y", function (d, i) { return i * gridSize; })
.style("text-anchor", "end")
.attr("transform", "translate(-6," + gridSize / 1.5 + ")")
.attr("class", function (d, i) { return ((i >= 0 && i <= 4) ? "dayLabel mono axis axis-workweek" : "dayLabel mono axis"); });
var timeLabels = svg.selectAll(".timeLabel")
.data(times)
.enter().append("text")
.text(function(d) { return d; })
.attr("x", function(d, i) { return i * gridSize; })
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(" + gridSize / 2 + ", -6)")
.attr("class", function(d, i) { return ((i >= 7 && i <= 16) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis"); });
var heatMap = svg.selectAll(".hour")
.data(data)
.enter().append("rect")
.attr("x", function(d) { return (d.hour - 1) * gridSize; })
.attr("y", function(d) { return (d.day - 1) * gridSize; })
.attr("rx", 4)
.attr("ry", 4)
.attr("class", "hour bordered")
.attr("width", gridSize)
.attr("height", gridSize)
.style("fill", colors[0]);
heatMap.transition().duration(1000)
.style("fill", function(d) { return colorScale(d.value); });
heatMap.append("title").text(function(d) { return d.value; });
var legend = svg.selectAll(".legend")
.data([0].concat(colorScale.quantiles()), function(d) { return d; })
.enter().append("g")
.attr("class", "legend");
legend.append("rect")
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height)
.attr("width", legendElementWidth)
.attr("height", gridSize / 2)
.style("fill", function(d, i) { return colors[i]; });
legend.append("text")
.attr("class", "mono")
.text(function(d) { return "≥ " + Math.round(d); })
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height + gridSize);
});
with this example i have successfully place the labels but unable to draw boxes. I have make many charts in nvd3 rhis is first chart in d3.js. anybody help?
how to append duplicate values from json array to another array? not remove from array
This array (catalog) contains duplicate values. I need to append duplicate values to an array.
here duplicate entries check by category and by name.
var catalog = {
products : [
{ category: 'fos', name: 'retek' },
{ category: 'fos', name: 'item' },
{ category: 'nyedva', name: 'blabla' },
{ category: 'fos', name: 'retek' },
]
};
var categories = [];
$.each(catalog.products, function(index, value) {
if ($.inArray(value.category, categories) == -1) {
//do nothing
} else {
if ($.inArray(value.name, categories) == -1) {
//do nothing
} else {
//add duplicate values to array
categories.push(value.name);
}
}
});
console.log(categories);
Put a js function inside a jQuery function
I've been working so hard to make a chart render automatically but now I've come to the situation where all the previously prepared data is not being useful.
I'm passing to a js chile some user data in order to render a chart...then I do some extra treatment in javascript to finish with the data preparation. I'm using a template which has a predefined way of showing the chart.
This is what I've done so far:
if ($('#interactive-chart').length !== 0) {
var previous = '';
var usersData = data['periodicity'];
var months = [[1,0], [2,0], [3,0], [4,0], [5,0], [6,0], [7,0], [8,0], [9,0], [10,0], [11,0], [12,0], [13,0]];
var overlapped = months.slice();
var monthConn = [];
for (var i = 0; i < usersData.length; i++) {
var user = usersData[i].vusr_user;
if (usersData[i].yearly == currentYear) {
if (user !== previous) {
previous = user;
if (i !== 0) {
monthConn.forEach(function(monthData){
overlapped[monthData[0]-1][1] = monthData[1];
});
var overlapped = months.slice();
var monthConn = [];
}
monthConn.push([usersData[i].month, usersData[i].count]);
}else{
monthConn.push([usersData[i].month, usersData[i].count]);
}
};
};
Next to that there is this jQuery predefined function:
$.plot($("#interactive-chart"), [{
data: data1,
label: "Page Views",
color: blue,
lines: {
show: true,
fill: false,
lineWidth: 2
},
points: {
show: true,
radius: 3,
fillColor: '#fff'
},
shadowSize: 0
}, {
data: data2,
label: 'Visitors',
color: green,
lines: {
show: true,
fill: false,
lineWidth: 2
},
points: {
show: true,
radius: 3,
fillColor: '#fff'
},
shadowSize: 0
}],
{
xaxis: {
ticks: xLabel,
tickDecimals: 0,
tickColor: '#ddd'
},
yaxis: {
ticks: 10,
tickColor: '#ddd',
min: 0,
max: 200
},
grid: {
hoverable: true,
clickable: true,
tickColor: "#ddd",
borderWidth: 1,
backgroundColor: '#fff',
borderColor: '#ddd'
},
legend: {
labelBoxBorderColor: '#ddd',
margin: 10,
noColumns: 1,
show: true
}
}
);
and I wish to pass the data from my function (the 1st one I wrote) to the second on where it says "data1", "data2"...
How am I suppose to do that?
Bootstrtap 3 Modal Window with 2 tabs and dynamic forms
I have a Bootstrap webpage with a Modal Window which has two tabs. There are two dinamic forms in the modal window. I am using this code for cloning fields in each of the form and I have two scripts for each of the tab but it not work for me. I can see fields from one form, cloning fields but when I click the second tab forms don't changing and I can see fields from the first tab only. What to do with it?
Script First Form
$(function() {
//console.log($('#template_add_form'));
var clone = function(tmpl) {
return $((tmpl.clone()).html())
},
$template = $('#template_add_form'),
formArray = [ clone($template) ], // init array with first row
$formEntries = $('#entries');
$(document).on('click', '.btn-add', function() {
//console.log('clicked');
formArray.push(clone($template));
updateForm();
// set focus to adding row = last element in array
$(formArray).last()[0]
.find('input')
.first()
.focus();
});
// remove not working yet
$(document).on('click', '.btn-remove', function(evt) {
var id;
// iterate over formArray to find the currently clicked row
$.each(formArray, function(index, row) {
//console.log(index, row.has(evt.currentTarget).length);
if ( row.has(evt.currentTarget).length == 1 ) {
//console.log(row.has(evt.currentTarget));
id = index; // click target in current row
return false; // exit each loop
}
});
//console.log('clicked', id);
formArray.splice(id, 1);
updateForm();
});
var updateForm = function() {
// redraw form --> problem values are cleared!!
//console.log(formArray);
var lastIndex = formArray.length - 1,
name; // stores current name of input
$formEntries.empty(); // clear entries from DOM becaue we re-create them
$.each(formArray, function(index, $input) {
//console.log(index, $input);
// update names of inputs and add index
//console.log('inputs', $input.find('input'));
$.each($input.find('input'), function(inputIndex, input) {
name = $(input).attr('name').replace(/\d+/g, ''); // remove ids
$(input).attr('name', name + index);
});
if (index < lastIndex) {
// not last element --> change button to minus
//console.log($input.find('.btn-add'));
$input.find('.btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}
$formEntries.append($input);
});
};
updateForm(); // first init. of form
$('form#loanform').submit(function(evt) {
evt.preventDefault();
var fields = $(this).serializeArray();
$.each(fields, function(index, field) {
//console.log(field.name);
//if ( field.name == 'extra' ) {
// console.log('extra', field.name, field.value);
// }
if ( field.name.contains('material') )
{ // field.name contains balance
console.log('material', field.name, field.value);
// now you can do your calculation
}
if ( field.name.contains('cena') )
{ // field.name contains balance
console.log('cena', field.name, field.value);
// now you can do your calculation
}
if ( field.name.contains('kol') )
{ // field.name contains balance
console.log('kol', field.name, field.value);
// now you can do your calculation
}
});
});
});
HTML First Form
<!-- script id="template_add_form" type="text/template" -->
<div class="entry input-group triple-input">
<select class="form-control" name="material" >
<option>...</option>
</select>
<select class="form-control" name="cena" >
<option>..</option>
</select>
<input type="text" placeholder="..." name="kol" class="form-control" />
<span class="input-group-btn">
<button class="btn btn-success btn-add" type="button" name="button" id="cloneButton"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
<!--//script-->
<form method="post" id="loanform" role="form" autocomplete="off">
<div id="entries"></div>
For second form I was changed ID names of fields, names of ID div in HTML and in the script (for example template_add_form to template_rab_form and entries to rab) and I get the first form on both tabs only.
And second question: how to add new names with personal ID to cloned fields?
if ( field.name.contains('name') )
{
console.log('name', field.name, field.value);
// now you can do your calculation
}