samedi 31 janvier 2015

Fade in background image on load


I want to load one of the random background image by using jquery. Below is the script I am using and it shows random background on refresh but without fadeIn effect. How can I create fadeIn effect onload. Note: I don't want to cycle random images.



$(document).ready(function() {
var images = ['01.jpg', '02.jpg', '03.jpg', '04.jpg', '05.jpg', '06.jpg', '07.jpg', '08.jpg', '09.jpg', '10.jpg'];

$('.about').css({'background-image': 'url(../img/bg/' + images[Math.floor(Math.random() * images.length)] + ')'});
('.about').fadeIn(1000);
});




How can I add an extra list function to this knockout javascript on Sharepoint?


So I have never really used Knockout before so I'm very new to this.


The pre-existing knockout means that when a certain value is clicked on a dropdown a certain list of values become available to select in the next dropdown. I'm now adding a second value to the first list which changes the values in the second dropdown. These dropdown values are all imported from 2 different sharepoint lists.



$.when(
$.getJSON('../_vti_bin/http://ift.tt/1JTvCgS'),
$.getJSON('../_vti_bin/http://ift.tt/1HqwNq9')

).then(function(apps, roles){
// both ajax calls are finished now
var rolesMap = {}; // {AppID1: [role1, role2], AppID2: [role3, role4]}
if (roles[0].d && roles[0].d.results) {
var r = roles[0].d.results;
for (var i = 0; i < r.length; i++) {
if (!rolesMap[r[i].ApplicationID]) {
rolesMap[r[i].ApplicationID] = [];
}
rolesMap[r[i].ApplicationID].push(r[i]);
}
}
if (apps[0].d && apps[0].d.results) {
var a = apps[0].d.results;
for (var i = 0; i < a.length; i++) {
var app = {
ApplicationID: a[i].Id,
ApplicationName: a[i].ApplicationName,
ApplicationDescription: a[i].ApplicationDescription,
roles: rolesMap[a[i].Id]
};
model.applications.push(app);
model.applicationMap[app.ApplicationID] = app;
}
}


else if(apps[1].d && apps[0].d.results) {
var a = apps[0].d.results;
for (var i = 0; i < a.length; i++) {
var app = {
ApplicationID: a[i].Id,
ApplicationName: a[i].ApplicationName,
ApplicationDescription: a[i].ApplicationDescription,
roles: rolesMap[a[i].Id]
};
model.applications.push(app);
model.applicationMap[app.ApplicationID] = app;
}
}


});


ASPX:



<td class="ms-vb">
Application:
<select data-bind="value: $data.selectedApp, options: $parent.applications, optionsText: 'ApplicationName', optionsCaption: 'Choose an Application'" style="width: 32px" name="Application list" id="dataBox">
</select>
<img src="../SiteAssets/helpbutton.png" class="helpbutton" onmouseover="displayAppHelpText(this);"/>
&nbsp; Role: <select data-bind="value: selectedRole, options: roles, optionsText: 'RoleNameValue', optionsCaption: 'Choose a Role'"></select>
<button data-bind="click: addSelectedRole" id="add_button">Add</button>
<img src="../SiteAssets/helpbutton.png" class="helpbutton" onmouseover="displayRoleHelpText(this);"/>

<span class="hidden">
<select class="appnames" data-bind="value: $data.selectedApp, options: $parent.applications, optionsText: 'ApplicationName', optionsCaption: 'App'"></select>
<select class="appdescriptions" data-bind="value: $data.selectedApp, options: $parent.applications, optionsText: 'ApplicationDescription', optionsCaption: ''"></select>
<select class="rolenames" data-bind="value: selectedRole, options: roles, optionsText: 'RoleNameValue', optionsCaption: 'Please select an Application first'"></select>
<select class="roledescriptions" data-bind="value: selectedRole, options: roles, optionsText: 'Description', optionsCaption: ''"></select>
</span>


So when I click an application I want to change the roll, however I am having problems with this. Thanks





Predictable Javascript array shuffle


I'm trying to predictably shuffle javascript arrays the same way each time the webpage is loaded.


I can shuffle the arrays randomly, but every time i reload the page it's a different sequence.


I'd like it to shuffle the arrays the same way every time the page loads. There are many arrays and they are part of a procedurally generated world.





How do you run multiple routes off of one route controller using iron-router?





Background:


I am making a blog using meteor and iron-router. I want to use a single controller for several different "category pages," which filter a list a blog articles in the yield region.


The Problem:


The article list does not get rerendered when the URL changes. I.e. the article list is not reactive. Interestingly, if I navigate back to the home page, the correct article list shows up.


The Question:


How do I make that article list change when I change between different routes on the category route controller?




Some example code:


Please note that the code for this whole project is available here.


Here is my Route Controller:



CategoryController = RouteController.extend({
action: function(){
this.render();
},
template: 'category',
data: function(){
return {category: this.params.category};
}
});

CategoryController.helpers({
articles: function(){
return Articles.find({category: this.params.category});
}
});


And here is the template it is rendering:



<template name='category'>
<div class="container">
<h2>{{category}}:</h2>
<ul>
{{#each articles}}
<li>
{{#linkTo route="article.show"}}
{{title}}
{{/linkTo}}
</li>
{{/each}}
</ul>
</div>
</template>




Resources:






Cannot access proper firebase item key to pass to delete function


Having a sticky issue with firebase. I am trying to get access to the long format ID which firebase auto-generates for each collection item (eg. -JgnIsMlTLaPuDMEtQP2) to pass to my delete function. I previously got it to work in a different angular app as follows:


HTML



<tbody ng-repeat="(key,employee) in employees">
<tr>
<td>{{employee.employeeName}}</td>
<td>{{employee.employeeAge}}</td>
<td>{{key}}</td> // the key param appeared perfectly in this case
<td>
<button class="btn btn-danger"
ng-click="deleteEmployee(key, employee.employeeName)">
delete <span class="glyphicon glyphicon-remove"></span>
</button>
</td>
</tr>
</tbody>


Javascript



$scope.deleteEmployee = function(key,name) {
// get ref to db collectionvar employeeRef = new Firebase("http://ift.tt/1yZ2hOj");
// append item key to the path and run remove method
var newRef = employeeRef.child(key);
newRef.remove();
// confirm delete
alert(name + " has been deleted");
}


The above code receives the correctly formatted key and deletes the item perfectly - which is immediately reflected in the view.


However, I'm trying it with a different app and the key value is being set to an incremental index (eg. 0,1,2,3,4...) and so it doesn't work when passed to the delete function. Here is the new code.


HTML



<div class="row">
<ul id="messages" ng-show="messages.length">
<li ng-repeat="(key, message) in messages | reverse">{{message.text}}
<small>{{key}}</small> // WRONG VALUE DISPLAYED HERE
<button class="btn btn-xs btn-danger" ng-click="delMessage(key)" label="Remove">Delete</button>
</li>
</ul>
</div>


Javascript



//delete message
$scope.delMessage = function(messageKey) {
var messageRef = new Firebase('http://ift.tt/1A9nTJy');
// append item key to the path and run remove method
var messageRef = messageRef.child(messageKey);
if( messageRef ) {
messageRef.remove();
console.log("DEL: " + messageRef); // this logs the endpoint with index number
console.log("Message removed successfully!");
} else {
console.log("uh oh...problem!");
}
};


The format of messageRef when logged to console is



http://ift.tt/15RCfRQ


but instead should be



http://ift.tt/1A9nTJA


I have tried every combination that I could find to get it to work but nothing fixes it so far. I'm not sure why it would work in the first piece of code and not the second. The only thing I can add is the app that isn't working was created via firebase-tools in the terminal whereas the working app is just some angular code with firebase bolted on. I have also tried changing remove() to $remove but that throws undefined method errors. I'm totally stumped. Any assistance is appreciated.





Drag images smooth on mobile devices with javascript


Hi i want to create a javascript application where i have to drag images around. I've broken it down to the minimum here (works only for touch events, needs jquery):





var draggable = $("#draggable")[0];
draggable.x = 0;
draggable.y = 0;

$("#draggable").bind('touchstart', function(e) {
draggable.lastmouse = e.originalEvent.touches[0];

});
$("#draggable").bind('touchmove', function(f) {
f = f.originalEvent.touches[0];
var newx = draggable.x + (f.clientX - draggable.lastmouse.clientX);
var newy = draggable.y + (f.clientY - draggable.lastmouse.clientY);
draggable.x = newx;
draggable.y = newy;
$(draggable).css('transform', 'translate3d(' + newx + 'px,' + newy + 'px,0)');
draggable.lastmouse = f;
});



<div class="map" id="draggable" style="width: 90%; height: 90%; position: absolute;">
<img src="http://ift.tt/1KgDXJP" width="100%" height="100%">
</div>



On a Computer it runs smooth, but on my GalaxyS4 its stuttering when i drag the image around, although i used translate3d. I thought it would be hardware accellerated.


Is there a way to get a native-app-like performance?





Use Kendo UI Flip Effects / Combined Effects for multiple items on the same page


I need to use kendo ui to display between 6-60 items. Each using the flip effect here http://ift.tt/1BJWV9u


The products will be loaded from the database with the unique id like this:



<div class="row">
<div class="col-md-4 product-container">
<div id="productID1" class="productID">
<div class="product">
<div id="product-back1" class="product-desc">
<p>BACK</p>
</div>
<div id="product-front1" class="product-image">
<p>FRONT</p>
</div>
</div>
</div>
</div>
<div class="col-md-4 product-container">
<div id="productID2" class="productID">
<div class="product">
<div id="product-back2" class="product-desc">
<p>BACK</p>
</div>

<div id="product-front2" class="product-image">
<p>FRONT</p>
</div>
</div>
</div>
</div>
<div class="col-md-4 product-container">
<div id="productID3" class="productID">
<div class="product">
<div id="product-back3" class="product-desc">
<p>BACK</p>
</div>
<div id="product-front3" class="product-image">
<p>FRONT</p>
</div>
</div>
</div>
</div>


The problem is I need multiple panels on the page how can I make each "front" and "back" click unique.



var el = kendo.fx($('div[id^=productID]')),
flip = el.flip("horizontal", $('div[id^=product-front]'), $('div[id^=product-back]')),
zoom = el.zoomIn().startValue(1).endValue(1);

flip.add(zoom).duration(200);

$('div[id^=product-front]').click(function () {
flip.stop().play();
});

$('div[id^=product-back]').click(function () {
flip.stop().reverse();
});


I've tried loading each item into an array but have not found a good way to assure the correct item will be flipped.





object inside object javascript google table


I'm trying to use Google's chart: http://ift.tt/1ppbI5g


I have some objects inside another object that I want to insert into the table. My question is this: do I have to put them into an array?


My code so far:


How do I get the objects from a JSON file:



function getTotalBundles() {
var totalBundles = {};
for (var i = 0, max = users.length; i < max; i++) {
var user = users[i];
for (var bundle in user.bundles) {
if (user.bundles.hasOwnProperty(bundle)) {
if (!totalBundles[bundle])
totalBundles[bundle] = 0;

++totalBundles[bundle];
}
}
}
return totalBundles;
}

function drawTable() {
var data = new google.visualization.DataTable();
var temp = getTotalBundles();

data.addColumn('string', 'Name');
data.addColumn('number', 'Purchased');
data.addRows(....);
}




Server-side plugin mechanism for Rails application


I have a Rails application that has the following attributes:


The application



  • can have a number of clients (web-browsers)

  • can run in different modes/programmes

  • can receive simple events (e.g. when a new client connects)

  • can output primitive information (for now just text)


So is one examples of what I mean by modes:


Mode 1: Whenever a new client is detected the new client should output "Hello Anyone" and all existing clients should output "Welcome!"


Mode 2: Whenever a new client is detected the new client gets assigned a random number and he "says" my number is "5". The other clients say "My number is still "XYZ".


Now this seems to be fairly simple and I have the whole client part (using Ajax polling) as well as the server part set up. Everything runs smoothly so far.


However, what I want to do now is extracting the mode-logic out into a pluggable architecture using javascript.


So the rough approach would be:



  1. The application is in a given mode

  2. An event happens

  3. The application processes the mode's javascript code with the event

  4. The application outputs any results and sends them to the clients (polling at the moment)


Since the whole stuff is event-driven I think javascript/coffeescript is a very good candidate for this. So the mode could be defined like so:



# Coffee
onClientConnect (stage, newClient)->
stage.sendToExistingClients('Welcome!')
newClient.send('Hello Anyone')


The variables stage and newClient are now some part of my JS API which are hooks for the mode to connect to. Also the onClientConnect method.


How can I execute this Javascript-based code on my server, provide the necessary hooks and process the events so that all the clients display their respective output?





return index of chaged handle on jquery-ui slider


I have a jquery ui slider :



$( "#slider" ).slider({
values: [ 10, 25,45,176 ],
max:190,
change: function( event, ui ) {
var index = $("#slider span").index(ui.handle);
$( "#index" ).text( "That was handle index #" + index );
}
});


i want to return the index of changed single handle. but handle object returns all spans ( handles). how can i do that?





Cant make two buttons use the same function in jquery with html


I have some code to add some content to a div when a button is clicked and in that code it adds a button called "teamReq_"+index+"_AddYear" (index is a number taken from a hidden input field).


So spamming the button will create divs: teamReq_1_AddYear,teamReq_2_AddYear,teamReq_3_AddYear etc


at the end of the function I run the following code:



document.getElementById("teamReq_"+index+"_AddYear").onclick = addYear;


addYear is a function defined later in the js file, however it only runs for the latest button created e.g. if I created 3 buttons it would only run for teamReq_3_AddYear, the other two would cause the web page to reload. How do I fix this? Full code for generating the div's:



document.getElementById("addTeam").onclick = addTeam; function addTeam() {
event.preventDefault();
var index = document.getElementById("varTeamsReq").value;
var existingHTML = document.getElementById("teamsReqTab").innerHTML;
existingHTML += "<div style=\"overflow:hidden; width:1000px\" id=\"teamReq_"+index+"\">";
existingHTML += " <div style=\"float:left\">";
existingHTML += " <input id=\"teamReq_"+index+"_Quantity\" type=\"number\" value=\"1\" min=\"1\" style=\"width:60px\">";
existingHTML += " </div>";
existingHTML += " <div style=\"float:left\" id=\"teamReq_"+index+"_MidText\">";
existingHTML += " &nbsp;students from year&nbsp;"
existingHTML += " </div>";
existingHTML += " <input type=\"hidden\" name=\"varTeamsReq_"+index+"_Years\" value=\"2\" id=\"varTeamsReq_"+index+"_Years\"/>";
existingHTML += " <div style=\"float:left; overflow:hidden;\" id=\"teamReq_"+index+"_Years\">";
existingHTML += " <div style=\"float:left\" id=\"teamReq_"+index+"_Year_1_Div\">";
existingHTML += " <input id=\"teamReq_"+index+"_Year_1\" type=\"number\" value=\"7\" min=\"7\" max=\"13\" style=\"width:60px\">";
existingHTML += " </div>";
existingHTML += " </div>";
existingHTML += " <div style=\"float:left\" id=\"teamReq_"+index+"_AddYear_Div\">";
existingHTML += " <button id=\"teamReq_"+index+"_AddYear\"><i class=\"fa fa-plus fa-1x\" style=\"transform: scale(1.3); color:#00FF00\"></i></button>";
existingHTML += " </div>";
existingHTML += " <div style=\"float:left\" id=\"teamReq_"+index+"_DelYear_Div\">";
existingHTML += " </div>";
existingHTML += " <div style=\"float:right\">";
existingHTML += " <button id=\"teamReq_"+index+"_Remove\"><i class=\"fa fa-minus fa-1x\" style=\"transform: scale(1.3); color:#FF0000\"></i></button>";
existingHTML += " </div>";
existingHTML += "</div>";
document.getElementById("teamsReqTab").innerHTML = existingHTML;
document.getElementById("varTeamsReq").value = parseInt(document.getElementById("varTeamsReq").value) + 1;
document.getElementById("teamReq_"+index+"_AddYear").onclick = addYear;
document.getElementById("teamReq_"+index+"_Remove").onclick = delTeam;


}


Full code for the addYear function:



function addYear() {
event.preventDefault();
var index = this.id.substring(8,this.id.length-8);
var year = document.getElementById("varTeamsReq_"+index+"_Years").value;
if (year == 7) {
document.getElementById("teamReq_"+index+"_AddYear_Div").innerHTML = "";
}
if (year == 2) {
document.getElementById("teamReq_"+index+"_DelYear_Div").innerHTML = "<button id=\"teamReq_"+index+"_DelYear\"><i class=\"fa fa-minus fa-1x\" style=\"transform: scale(1.3); color:#FF0000\"></i></button>";
document.getElementById("teamReq_"+index+"_DelYear").onclick = delYear;
}
for (i = 2; i < year; i++) {
document.getElementById("teamReq_"+index+"_Year_"+i+"_Div").innerHTML = "&nbsp;,&nbsp;<input id=\"teamReq_"+index+"_Year_"+i+"\" type=\"number\" value=\"7\" min=\"7\" max=\"13\" style=\"width:60px\"/>";
}
var existingHTML = document.getElementById("teamReq_"+index+"_Years").innerHTML;
existingHTML += " <div style=\"float:left\" id=\"teamReq_"+index+"_Year_"+year+"_Div\">";
existingHTML += " &nbsp;or&nbsp;";
existingHTML += " <input id=\"teamReq_"+index+"_Year_"+year+"\" type=\"number\" value=\"7\" min=\"7\" max=\"13\" style=\"width:60px\"/>";
existingHTML += " </div>";
document.getElementById("teamReq_"+index+"_Years").innerHTML = existingHTML;
document.getElementById("varTeamsReq_"+index+"_Years").value = parseInt(document.getElementById("varTeamsReq_"+index+"_Years").value) + 1;


}





Change the color of a Three.js globe


There is a really cool Three.js demo which has a 3D Globe: http://ift.tt/1nOqFuC


I'd like to change the color of the globe itself from black to navy blue. I'm looking through all the source files and keep changing things but nothing is having an effect on the globe color.


I don't know Three.js or WebGL that well. Might someone help?





What happens when an iPhone/iPad keyboard is shown/closed in Safari?


I'm trying to understand what happens after the "Done" button is clicked on the iPhone/iPad keyboard when viewing a webpage in Safari, specifically what events are fired.


From what I can gather so far, the text box that was selected loses it's focus.


Is this all that happens, or does the whole window lose it's focus?


I'm also interested to know if the showing of the keyboard causes any resize events to be fired?





Best way to deploy a Content Management System for a relatively static website?


I'm going to create a content management system for a website I am producing for a client.


The website will be a club-page which will allow inquiries to join the club, registration as well as event pages that will include photos and such.


I was wondering what the best way to create a content management system where by the admin can add new event pages, or edit existing information such as titles, headings and paragraphs. I also want to produce a way of adding new headings and paragraphs within the page.


I'm not sure on the best method of adding new tags to an existing HTML document, or what should be included in the homepages' HTML since new tags and content will need to be added after.


This is a given project so using an already existing CMS solution is out of the question.


To give you a flavor of what I'm after, my first solution was to create a homepage with pre-determined tags with id's such as <p id='p1'></p> I was then going to store data in the database with columns 'tag' and 'content' i.e 'tag' = p1 and 'content = "This is a paragraph".


When the user initially visits the homepage, it would fire an ajax request to get all the data from the database and inject it into the tags based on the 'tag' entry. like, if 'tag' = p1 then getElementById("p1").innerHTML...


However, this approach would require me to know what tags to put in the html document. Alternatively I could just store all the homepage's content in one big database entry and return the entirety of it when the page loads. Although I'm sure it's pretty bad practise to request and process this much data just to display a homepage... Or is it okay to do so?


Any help/links you can shed some light on this problem will be greatly appreciated.


Many thanks, Mike





Need help on a simple Jquery practice


I've just started to practice Jquery at these days. Could you please have a take look at the below link and give me some advise on how to validate my input for only jpeg extension.



$('#submit').click( function() {
var val = $('#URL').val();


if(val !== "") {
$('#URL').val(function (){
$('#frame').fadeOut(800, function(){
$(this).css({backgroundImage: "url("+val+")"});
$(this).fadeIn(800);
});

});
}
else{
$('#lightbox, #feedback').slideDown(700, function(){
$("body").click(function() {
$('#lightbox, #feedback').slideUp(700);
return false;
});
});
}
return false;


Thanks in advance.


Regards.


Özgün





Change href in html


I have next code, but it's don't work:



<html>
<head>
<title>Title</title>
</head>

<body>
<script type='text/javascript'>
window.onload = function(){
var links = document.getElementsByTagName('A');
for(var i = 0; i < links.length; i++){
links[i].href = 'test.html';
}
}
</script>
<ul>
<li><a href = 1.html>1.</a></li>
<li><a href = 2.html>2.</a></li>
<li><a href = 3.html>3.</a></li>
</ul>
</body>
</html>


I need to change ALL links, on 'test.html'. Without JQuery.





jQuery/JavaScript delay and display


I want to cycle through an array and display each element individually, and then remove it. Sort of like this fiddle, but I don't want it to go forever.


I tried using jQuery because I thought it would be easier, but I am clearly missing something. Can anyone help?


Here is my attempt, but it just goes straight to the last element in the array.



var list = [1,2,3,4,5,6];
var length = list.length;

for(i = 0; i < length; i++) {
$('#nums').html(list[i]).delay(750);
}


Oh, and I don't care if it's jQuery or vanilla JavaScript. Either is fine by me.





How to get last created id from sqlite data base using javascript?



$('#CreateCustomer').submit(function () {
if ($('#CreateCustomer').parsley('validate')) {

var name = $('#pname').val();
var city = $('#pcity').val();
var address = $('#paddress').val();
var mail = $('#pmail').val();
var phone1 = $('#pphone1').val();
var phone2 = $('#pphone2').val();
db.transaction(function (tx) {
tx.executeSql(InsertPerson, [name, mail, city, address, phone1, phone2], onError);
});
}
ResetForm();
$('#close').click();
location.href = "view.html?id=" + id;
return false;




How to freeze properties inside a contructor function in JavaScript


I'm trying to make the properties inside a constructor function immutable, i.e. the properties should not be altered either with a dot or bracket notation. E.g. I have my constructor function:



function OnceNamedOne() {
Object.freeze(this.firstName = 'John');
Object.freeze(this.lastName = 'Doe');
this.fullName = this.firstName + ' ' + this.lastName;
}


I basically want to freeze the properties and hard wire their values as in the function. So, when an instance is created:


var me = new OnceNamedOne(); and when the value I try to change the property value, it should not work - that is the following should not assign 'John' to first name: me.firstName = 'John';.


How could I do this?





Session.set() upon route event in Meteor


I have this functionality associated with clicking a button:



'click .single-speaker-info a': function(ev, speaker){
ev.preventDefault();
Session.set('selectedDocId', this._id);
}


But I'd like it to happen upon hitting this route



Router.route('speaker', {
path:'/speakers/:_id',
template: 'speaker',
data: function(){
return Speakers.findOne(this.params._id);
},

//my attempted solution
selectedDocId: function(){
Session.set('selectedDocId', this._id);
}
});


But I can't find any documentation on how to execute a method on a route.


Here is the Template.helper Im using to get the property Im setting



Template.speaker.helpers({

editingDoc: function(){
return Speakers.findOne({_id: Session.get('selectedDocId')});
}

});




How do I get my HTML5 Location result in a global variable?



function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geen geolocatie hier.";
}

function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var total = String(lat).concat(',', String(lon));
}


How do I get that last 'total'-variable to be usable in other functions? And why doesn't declaring a global variable in the showPosition() function seem to work?





Javascript - checking input if it matches what i want


I need to create a simple function that takes the parameter 'str'. this then needs to checked to see if it is in the format of "dd/mm/yyyy" and obviously return false if it doesn't or if for example the 'dd' part is 34 .. because there aren't 34 days in a month





Why use script type multiple times


With the following working code I had a question about some of the needed syntax. Why do you need to set the script type in multiple places in the html code instead of just once in order to get it to work? Shouldn't there be a way to only set it once and then have the rest of the code be able to read your script?



<html>
<head>
<title>Assignment 2</title>
<script type="text/javascript">

var name1 = prompt("What is your name?");
var name2 = prompt("What is the second person's name?");

function Greet(who1, who2)
{
alert("Hello " + who1 + " and " + who2 + ". Welcome to my website.");
}

</script>
</head>
<body>
<h1>JavaScript Greet Function<h1>
<script LANGUAGE="JavaScript">
Greet(name1,name2);

</script>
</body>
</html>




how to save current url using javascript [Imacros]


I am searching for such method to save the current url of the webpage to a file. after alot search I found this working script:



SET !ERRORIGNORE YES


SET !EXTRACTADD {{!URLCURRENT}} SAVEAS TYPE=EXTRACT FOLDER=c:\ FILE=URL.CSV


But the point is that how to use this in javascript . I just tried as following :



var link;


link +="SET !ERRORIGNORE YES": link +="SET !EXTRACTADD {{!URLCURRENT}}";`` link +="SAVEAS TYPE=EXTRACT FOLDER=c:\ FILE=URL.CSV";


but this is not working for me . I am just a noob , Help me out with a easy way :)


Thanks in Advance





Populate ul in html with JSON data


Hi im trying to populate ul in html with JSON, i have tried many solutions from this site, but im not having much luck, any suggestions would be gratefully appreciated. Thanks


my code :



<script>
$.getJSON('/simplepie/round/alltables.json', function (data) {
var o = null;
var myArray = new Array();
document.open();
for( var i = 0; i < data.length; i++ )
{
o = data[i];
myArray.push('<li>' + o.title + '</li>');
//document.write(o.source + " <br>" + o.description + "<br>") ;
myArray.push(o.source);
makeUL(o.source);
}

//document.close();
// document.write('Latitude: ' + data.id + '\nLongitude: ' + data.title + '\nCountry: ' + data.description);

function makeUL(array) {
var list = document.createElement('ul');
for(var i = 0; i < array.length; i++) {
var item = document.createElement('li');
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}


return list;
}

});

</script>

</head>
<body>
<ul id="ct"></ul>
</body>




Famo.us Multiple Touch Events Prevent Click Event


I have a surface that on 'click' on touch devices needs to fire an event even when other touches are occurring on the screen.


I'm using the FastClick shim provided by Famo.us, but it doesn't seem to handle touchstart->touchend clicks while other touch events are present on the window.


I've set up a codepen portraying my issue. Once you have the codepen open on a touch device, press and hold a finger down anywhere on the screen and then try to trigger the click event on the surface - you'll see it doesn't work.


The code is very basic:



var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface');
var EventHandler = require('famous/core/EventHandler');
var Transform = require('famous/core/Transform');
var Timer = require('famous/utilities/Timer');
var FastClick = require('famous/inputs/FastClick');

var StateModifier = require('famous/modifiers/StateModifier');
var Modifier = require("famous/core/Modifier");


var context = Engine.createContext();

var handler = new EventHandler();

// a modifier that centers the surface
var centerModifier = new Modifier({
origin : [0.5, 0.5],
align: [0.5, 0.5]
});

var center = context.add(centerModifier);


var button = new Surface({
size:[150,150],
properties: {
color: '#222',
backgroundColor: '#CCC',
textAlign: 'center',
lineHeight: '150px'
},
content: 'Tap/Click me!'
});

button.on('click', function() {
button.setContent("Tapped!!");
Timer.setTimeout(function(){
button.setContent('Tap/Click me!');
},750);
});

center.add(button);


Given that I'm developing an app for a multi user touch table:


How can I listen for click events on surfaces while other touches are firing elsewhere on the screen?





Visual Studio 2013 client-side debugging tools: How to turn off?


When you F5 a web app in Visual Studio, your page contains this:


enter image description here


I am having trouble with some javascript on a page and have the feeling that the javascript behind the vs tooling could interfere.


Is there any way to turn this off?





Angular JS directives doesn’t work in visualforce(salesforce)?


Inside a visual force page (as a container), I have created a custom directive in angular JS but it’s not working. In fact, the directive is not even being called! Though this works perfectly fine in the JSFiddle


Below is the custom directive.When I use this directive in the HTML markup, it never show anything on the console log. I have created multiple directives and seeing the same behavior. I believe there is a bug when using custom directives inside the visualforce container.Has anyone of you have faced the same issue? Any help would be greatly appreciated.


Thanks! -SS


UPDATE


Here is the JSFiddle for Custom directive that works fine but when I use it in visual force page, it doesn’t work.( Even though the directive has a console.log, nothing appears in console. This proves that the directive is not being called) http://ift.tt/1wO8ZkS


Please note: This directive strips off everything before and after underscore in the OppName. For example: If OppName is “111111_Test_123445" then output is “Test"


Here is the visual force page and a controller:


PAGE:



<apex:page docType="html-5.0" controller="SalesActions">
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"/>
<apex:includeScript value="http://ift.tt/1CwQKFr"/>
</head>
<!-- HTML FOR APP -->
<!-- To use bootstrap with visualforce everything needs to be wrapped with "bs" class-->
<div ng-app="salesApp" class="bs">
<div ng-controller="salesController">

<div ng-repeat="sfResult in salesforceResponse">
<table>
<tr ng-repeat="opp in sfResult.opportunities">
<td>
<span opp-name="" input="opp.Name">
{{opp.Name}}
</span>
</td>
</tr>
</table>
</div>
</div>
</div>

<!-- ACTUAL ANGULAR JS APP : Later on move this to salesworkspace.js-->
<script type = "text/javascript">
var ngApp = angular.module('salesApp', []);
//Opp Name directive
ngApp.directive('oppName', function () {
return {
restrict: 'A',
scope: {
input: '='
},
link: function (scope, element, attrs) {
console.log('Input: ', scope.input);
var input = scope.input;
if (!input) {
return;
}
// AccountName_Test_123445
if (input.indexOf('_')) {
scope.input = input.split('_')[1];
}
}
};
});

ngApp.controller('salesController', ['$scope',
function($scope) {

$scope.salesforceResponse = [];
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.SalesActions.getAllAccounts}',
function(result, event) {
if (event.status) {
$scope.$apply(function() { //Use Apply as the scope changed outside Angular Context?
$scope.salesforceResponse = result;
console.log($scope.salesforceResponse);
});
} else {
console.log(event);
}
}
);
} //End of function
]); //End of Controller method
</script>
</apex:page>


CONTROLLER: salesActions.cls



public with sharing class SalesActions {

public SalesActions() { } // empty constructor

@RemoteAction
public static List<accountWrapper> getAllAccounts() {
List<accountWrapper> accountResponse = new List<accountWrapper>();
List<account> accs = [SELECT Id, Name, Type, Strategic_Account_Management__c,
(SELECT Id FROM Opportunities) ,
(SELECT Name FROM Contacts)
FROM Account
Order by Name]; //Add a Filter here. WHERE ownerId = :Userinfo.getUserId();

Set<Id> accountIds = new Set<Id>();
for(account acc : accs) {
accountIds.add(acc.Id);
}

Map<Id,Opportunity> oppIdToOpp = new Map<Id,Opportunity>([
SELECT Id,Name, Account.Name, Agency__r.Name, Campaign_EVENT__c,Rate_Type__c,StageName,Amount,CurrencyISOCode,
Probability,CampaignStartDate2__c,CampaignEndDate2__c,Contact__c,Sales_Notes__c,
(SELECT SplitAmount, SplitOwner.Name,SplitPercentage, Split__c FROM OpportunitySplits)
FROM Opportunity WHERE AccountId IN :accountIds]// Remove WHERE AccountId =:accountId and Add WHERE account.ownerId=:UserInfo.getId();
);


Map<Id,List<Partner>> accountIdToPartners = new Map<Id,List<Partner>>();
for(Partner p :[SELECT AccountFromId,AccountTo.Name FROM Partner WHERE AccountFromId IN :accountIds]) {
if(accountIdToPartners.containsKey(p.AccountFromId)) {
accountIdToPartners.get(p.AccountFromId).add(p);
} else {
accountIdToPartners.put(p.AccountFromId, new List<Partner>{p});
}
}
for(Account acc : accs) {
accountWrapper accWrapper = new accountWrapper();
accWrapper.account = acc; // This will add all the accounts and related contacts
accWrapper.opportunities = new List<Opportunity>();
accWrapper.partners = new list<Partner>();
if(accountIdToPartners.containsKey(acc.Id)){
accWrapper.partners = accountIdToPartners.get(acc.Id);
}
for(Opportunity opp : acc.Opportunities) {
accWrapper.opportunities.add(oppIdToOpp.get(opp.Id)); // This will add all the opportunties and opportunitySplits
}
accountResponse.add(accWrapper);
}
return accountResponse;
}

public class accountWrapper {
public Account account { get; set; }
public List<Partner> partners { get; set; }
public List<Opportunity> opportunities { get; set; }
}
}




kendo date dialog on click of input box


I have a kendo Date picker it is functioning well.


On click of icon in input box I am able to open date dialog and it is working. But I want this dialog should also open in click of input box as well..



<h4>Select date:</h4>
<input kendo-date-picker
ng-model="dateString"
k-ng-model="dateObject" />


Demo : http://ift.tt/1o9VQnm


Can anyone guide me ?





javascript of recaptcha is not working


please help...


when i use the code below used in the form it does not open the form at all in the lightbox / fancybox. but when i remove it it works.


Code:



<script type="text/javascript">
Recaptcha.create("6Ld5necSAAAAAMNoodwSDBwEWAQi3Yd3VHHSsZnr",
"recaptcha",
{
theme: "red",
callback: Recaptcha.focus_response_field
}
);
</script>


Button is like this:



<li class="email gradient_button"><a href="forms/friends.php?recaptcha" class="fancybox_div">Email to a Friend</a></li>


and the form is like this:



<form name="email_friend" method="post" class="ajax_form">
<table>
<tr><td>Name: </td> <td> <input type="text" name="name"></td></tr>
<tr><td>Email: </td> <td> <input type="text" name="email"></td></tr>
<tr><td>Friends Email: </td> <td> <input type="text" name="friends_email"></td></tr>
<tr><td colspan="2">Message:<br>
<textarea name="message" class="fancybox_textarea"></textarea></td></tr>
<tr><td colspan='2'><br><div id='recaptcha'></div></td></tr> <tr><td colspan="2"><input type="submit" value="Submit" class="pull-left"></td></tr>
</table>
</form>


The full file of form looks like this:



<h3>Email to a Friend</h3>

<form name="email_friend" method="post" class="ajax_form">
<table>
<tr><td>Name: </td> <td> <input type="text" name="name"></td></tr>
<tr><td>Email: </td> <td> <input type="text" name="email"></td></tr>
<tr><td>Friends Email: </td> <td> <input type="text" name="friends_email"></td></tr>
<tr><td colspan="2">Message:<br>
<textarea name="message" class="fancybox_textarea"></textarea></td></tr>
<tr><td colspan='2'><br><div id='recaptcha'></div></td></tr> <tr><td colspan="2"><input type="submit" value="Submit" class="pull-left"></td></tr>
</table>
</form>

<script type="text/javascript">
Recaptcha.create("6Ld5necSAAAAAMNoodwSDBwEWAQi3Yd3VHHSsZnr",
"recaptcha",
{
theme: "red",
callback: Recaptcha.focus_response_field
}
);
</script>


when i remove the javascript part it opens the form in lightbox / fancybox but with this code it does not open anything.


can you please tell me the issue???





Google Apps Script Bad value expextion


I'm getting a "bad value on line 4"... I don't know why. I'm trying to make a Google sheet that automatically opens to an assigned tab based on gmail address for a large team. Please help!



function onOpen() {
var email = Session.getActiveUser().getEmail();
var username = email.slice(0,-9);
var ss = SpreadsheetApp.openById(username);
SpreadsheetApp.setActiveSpreadsheet(ss);
}




Javascript - How are things broken?



var myName = 4;

function myName() {
console.log("xxxx");
}
console.log(typeof myName); //Number

var myNamex;

function myNamex() {
console.log("xxxx");
}
console.log(typeof myNamex); //function


Please refer the fiddle - http://ift.tt/1tLtinZ



console.log(typeof myName);


The above log statement logs different value, the only difference is that the variable is assigned a value in one place, and not in another.


Can you tell me how are both code snippet broken down, considering hoisting, closure or any that can be applied.





Detecting Browser Back Button after using history.pushState


I have a three-stage login form that shows/hides content on the page as progress is made. When the user proceeds from step 1 to step 2, I call the following:



var stateObj = { foo: "bar" };
history.pushState(stateObj, "", "");


And I see the browser back button enable. Now, I'm trying to catch the back button click so I can hide/show content (for example - back to stage 1) accordingly. How can I detect the browser back button in this scenario? I don't want the url to change, I just want to call some JS function when the user hits back. I am targeting modern desktop/mobile browsers.





get a smooth animation for a canvas game


How to get a better animation, dinamically, even when browser is busy or idle, for different devices which have different hardware capacity.


I have tried many ways and still cannot find the right way to make the game to display a better animation.


This is what i tried:



var now;
var then = Date.now();
var delta;

window.gamedraw = function(){

now = Date.now();
delta = now - then;

if(delta > 18){
then = now - (delta % 18);
game_update();
}

}

window.gameloop = setInterval(window.gamedraw,1);


18 is the interval value to update the game, but when browser is busy this interval is not good, and it needs to lower. How to get a better animation dinamically, even when browser is idle or busy ?


I suppose that the interval value is the problem, because if interval is lower then game animation is very fast, if this value is 18 then game animation is good but not when browser is busy, and I do not have idea how to change it dinamically.





Printing with bluetooth in phonegap


I'm needing of help for printing text in my aplication phonegap through of bluetooth of device...


I'm using this plugin for phonegap: http://ift.tt/1tLMPEU


but not working. I'm testing the android, I performed pairing the device put in applying appears that there is no active devices ...


Added this way in my files ...


Config.xml:



<feature name="BluetoothSerial">
<param name="android-package" value="com.megster.cordova.BluetoothSerial"/>
</feature>

<source-file src="src/android/com/megster/cordova/BluetoothSerial.java"
target-dir="src/com/megster/cordova"/>
<source-file src="src/android/com/megster/cordova/BluetoothSerialService.java"
target-dir="src/com/megster/cordova"/>

<!-- kludge for 2.9 -->
<source-file src="src/android/org/apache/cordova/api/Dummy.java"
target-dir="src/org/apache/cordova/api"/>


AndroidManifest:



<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />


This correct? What was missing?





First Time Web Services in ASP.NET VB


I am attempting to call a web service using JS from an asp.net website (VB) client side. I have used web services before but never set one up. I want to run async updates and queries. Any help would be great, similar examples, or better practices. Cant post images...


I believe I am having issues with Namespaces and proper calling of the methods from client events. Maybe something with the webconfig?


What I have done so far:

Make a new asp website in visual studio (website1). Add a new .asmx file named WebService.asmx. Uncomment System.Web.Script.Services.ScriptService(). Create a service reference using the wizard (ServiceReference1). On default.aspx add the script manager. Create button onclick and function. Then I run and I get this error on the js.


How I'm trying to call the service, I have done it like this in the past. One a system that was not mine. Does this method work?:



function test() {
ServiceReference1.WebService.HelloWorld();
}
<input type="button" onclick="test()"/>


What the WebService.asmx looks like, I have no NameSpace for that test. Should there be one?:



Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
Inherits System.Web.Services.WebService

<WebMethod()> _
Public Function HelloWorld() As String
Return "Hello World"
End Function

End Class


The app_reference successfully imports and the webservice runs alone fine. Also my webconfig:



<?xml version="1.0"?>

<!--
For more information on how to configure your ASP.NET application, please visit
http://ift.tt/1eW0XAj
-->

<configuration>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>

<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="WebServiceSoap" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:55800/WebService.asmx" binding="basicHttpBinding"
bindingConfiguration="WebServiceSoap" contract="ServiceReference1.WebServiceSoap"
name="WebServiceSoap" />
</client>
</system.serviceModel>
</configuration>


JS fires and breaks on webservice line with this message:



Unhandled exception at line 13, column 13 in http://localhost:55800/Default.aspx

0x800a1391 - JavaScript runtime error: 'ServiceReference1' is undefined


Any advice?





JavaFX WebView URL.createObjectURL undefined


I'm using JavaFX 8 embedded WebView. I want to build Blob URL from an Blob image. But, URL.createObjectURL gives me undefined. Is there any way (shim or eg.) to create Blob URL from Blob object in JavaFX 8 WebView environment??





Detecting html/js support custom date/select/multiselect input


Sorry, this question might not be the best worded question, please feel free to advice if i should change (if i can change).


Background:


Different browsers/OS's render html differently, we all know this. One of the significant things is, how certain form tags work.


Eg.



<select>
<option>option 1</option>
</select>


In desktop browsers, we see a dropdown, but in ios/android, we see a OS level modal/popup.


Other obvious tags are, multiselect, and input type "date" (nice date selector pops up on ios/android as opposed to the desktop simple text field).


Question:


So as a html/js developer, is there any way to detect if the current browser renders these tags differently?


Eg. its in good practice to let users select date using the most native thing you can, however, its not nice to tell them to type it out. So if the os/browser has a pre-made modal for date, i want to show the native implementation, and if no such implementation exists, then display a custom date picker.


Sure i can use a library to differentiate ios/android/pc, but thats not exactly what im looking for. is there a way to actually check if the browser supports custom behaviour for these tags?





Insert Image as Large as Possible in Google Doc using App Script


I'm trying to automate putting images in a Google Doc with Google App Script. I want an image (taken from drive) to take up as much space on the page as possible. I tried to do this with...



var element = cursor.insertInlineImage(image);
if (element) {
//element.setBold(true);
element.setHeight(DocumentApp.getActiveDocument().getBody().getPageHeight());
element.setWidth(DocumentApp.getActiveDocument().getBody().getPageWidth());
} else {
DocumentApp.getUi().alert('Cannot insert image at this cursor location.');
}


This causes a border on the left and bottom of about two inches. As I'm using a page with no margins, it should report the entire page size, but it's not. Is there any way to do this in Google App Script?


Thank you.





Cordova- taking picture


so I'm still pretty new to cordova and right now, I'm using it to make an app and I'm trying to take a picture and then save it. Right now, I can't take a picture. All I have is a button and in the corresponding javascript file, a function is called when the button is pressed. I started off by running 'cordova plugin add org.apache.cordova.camera'. This is what I tried:



document.addEventListener("deviceready', onDeviceReady);

function onDeviceReady() {

$('#picture').on('click',function() {
takePicture();
}

function takePicture() {

if (!navigator.camera) {
alert("Camera API not supported", "Error");
return;
}

navigator.camera.getPicture(function(imageURI) {
alert("test");
}, function(err) {
alert("Inside err");
}, cameraOption);

/*navigator.camera.getPicture(function(imagePath) {
alert("test");
document.getElementByID("photoImg").setAttribute("src", imagePath);
alert("Got picture");
}, function() {
alert("Photo canceled");
}, {
destinationType: navigator.camera.DestinatonType.FILE_URI
});*/


}
}


I got the function from http://ift.tt/14zMPw5 and I also tried the second from another place, but the camera doesn't come up in either one. Also, I inserted some alerts inside and none of them appear, so I'm a bit confused.


Does anyone have any suggestions how I can get the camera to show up?





Javascript - What problems are associated with declaring a prototypical method of a parent function *inside* the parent function's body?


Stylistically, I prefer this structure:



var Filter = function( category, value ){
this.category = category;
this.value = value;

// product is a JSON object
Filter.prototype.checkProduct = function( product ){
// run some checks
return is_match;
}

};


To this structure:



var Filter = function( category, value ){
this.category = category;
this.value = value;
};// var Filter = function(){...}

Filter.prototype.checkProduct = function( product ){
// run some checks
return is_match;
}


Functionally (har har), are there drawbacks to stucturing my code this way? Will adding a prototypical method to a parent function object inside the parent function's body ( i.e. before I even finish my parent function's expression statement ) cause unexpected scoping issues?


I've used the first structure before with success, but I want to make sure I'm not setting myself for a debugging headache, or causing a fellow developer grief and aggravation due to bad coding practices.





Area chart not filling up


I have a chart that I've been building, but for some reason, it isn't displaying as an area chart - at least, not smoothly. It's very spikey, and doesn't look very good. My data points are rather strange, but is there any way to have them transition more smoothly?


You can view what the chart looks like at http://ift.tt/15VEFyI


I want it to look more like this chart: http://ift.tt/1cCa3Ov (and I copied a large portion of this code to do so, so I'm not sure why it is displaying in this odd way.)


Thanks!


Here is the full code below. For reference, there are data points at every point in time (which is every 3 hours).



function InitChart() {

var lineData = [];
for (i = 0; i < Math.round(totaltime / interval); i++)
{
lineData[i] = {
"timeinterval": Date.now() - (i * interval * 1000),
"reactionrate": reactionratebyinterval[i],
"reach": reachbyinterval[i],
"engagement": engagementbyinterval[i]
};
}

var margin = {top: 10, right: 10, bottom: 100, left: 40},
margin2 = {top: 430, right: 10, bottom: 20, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
height2 = 500 - margin2.top - margin2.bottom;

var parseDate = d3.time.format("%b %Y").parse;

var x = d3.time.scale().range([0, width]),
x2 = d3.time.scale().range([0, width]),
y = d3.scale.linear().range([height, 0]),
y2 = d3.scale.linear().range([height2, 0]);

var xAxis = d3.svg.axis().scale(x).orient("bottom"),
xAxis2 = d3.svg.axis().scale(x2).orient("bottom"),
yAxis = d3.svg.axis().scale(y).orient("left").ticks(5);

var brush = d3.svg.brush()
.x(x2)
.on("brush", brushed);

var svg = d3.select("body").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 + ")");

svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);

var focus = svg.append("g")
.attr("class", "focus")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var context = svg.append("g")
.attr("class", "context")
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");

var data = lineData;

var areareach = d3.svg.area()
.x(function(d) { return x(d.timeinterval); })
.y0(height)
.y1(function(d) { return y(d.reach); })
.interpolate("monotone");

var areaengagement = d3.svg.area()
.x(function(d) { return x(d.timeinterval); })
.y0(height)
.y1(function(d) { return y(d.engagement); })
.interpolate("monotone");

var areareachbrush = d3.svg.area()
.x(function(d) { return x2(d.timeinterval); })
.y0(height2)
.y1(function(d) { return y2(d.reach); })
.interpolate("monotone");

var areaengagementbrush = d3.svg.area()
.x(function(d) { return x2(d.timeinterval); })
.y0(height2)
.y1(function(d) { return y2(d.engagement); })
.interpolate("monotone");

x.domain(d3.extent(data.map(function(d) { return d.timeinterval; })));
y.domain([0, d3.max(data.map(function(d) { return d.reach; }))]);
x2.domain(x.domain());
y2.domain(y.domain());

focus.append("path")
.datum(data)
.attr("class", "areareach")
.attr("d", areareach);

focus.append("path")
.datum(data)
.attr("class", "areaengagement")
.attr("d", areaengagement);

focus.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);

focus.append("g")
.attr("class", "y axis")
.call(yAxis);

context.append("path")
.datum(data)
.attr("class", "areareach")
.attr("d", areareachbrush);

context.append("path")
.datum(data)
.attr("class", "areaengagement")
.attr("d", areaengagementbrush);

context.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxis2);

context.append("g")
.attr("class", "x brush")
.call(brush)
.selectAll("rect")
.attr("y", -6)
.attr("height", height2 + 7);

function brushed() {
x.domain(brush.empty() ? x2.domain() : brush.extent());
focus.select(".areareach").attr("d", areareach);
focus.select(".areaengagement").attr("d", areaengagement);
focus.select(".x.axis").call(xAxis);
}
}




Cordova not running normally


The problem is:


I have index.html with this code:



<script type="text/javascript" src="../platforms/android/assets/www/cordova.js">


When I run this file in a browser, there is alert:



gap_init:2



Click "Ok" and I have second alert:



[true] gap:[null,"App","overrideBackbutton","App1966010284"]



In my console output I have: Endless loop



processMessag failed: invalid message: " "



Question: How I can fix this?


Linux Ubuntu 14.04, cordova v. 4.2.0, phonegap v. 3.6.3-0.22.0


Thank you!





JQuery validate not working on ajax loaded form


I have a form (with only 1 field) which is loaded via AJAX inside a div (id="area"). The form has a .validate function attached. But when it is not working. I have tried wrapping up the form by its parent container as shown below, but still unable to validate. Please let me how this can be fixed. This is the validate function -



$("#area").on("show", function () {

$("#myform").validate({
debug: true,

rules: {

TypeId: {
required: true
}
},

errorPlacement: function (error, element) {

// changes icon to red if error

var $icon = element.next();
$icon.removeClass("glyphicon-asterik glyphicon-ok-sign successicon");
$icon.addClass("glyphicon-remove-sign erroricon");
$icon.css('opacity', '1.0');
},

success: function (label, element) {

// changes icon to green if success

var $icon = $(element).next();
$icon.removeClass("glyphicon-asterik glyphicon-remove-sign erroricon");
$icon.addClass("glyphicon-ok-sign successicon");
$icon.css('opacity', '1.0');

}
})();

return false;
});


Thanks in advance.





Not all data sent using $http.post angularjs


why is it that whenever I send data to my server from my mobile application (Ionic Framework) not all data is sent?



$http({
method: 'POST',
url: 'http://remoteserver/data',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: { image: $scope.imgURI,
facebook_id: localStorage.facebook_id,
token: localStorage.accessToken,
location: localStorage.location,
lon: localStorage.longitude,
lat: localStorage.latitude
}
}).success(function (suc)
{
localStorage.removeItem('longitude');
localStorage.removeItem('latitude');
localStorage.removeItem('location');
alert(JSON.stringify(suc));
})
.error(function(err){alert(JSON.stringify(err));});


The location after is undefined when the server receives it. When in fact, I alert it to check if its not empty. How can I fix this? Of all the data sent to my server, only the location is missing. The location is the reversed geocoding of the latitude and longitude. I just put it in my mobile to reduce the over use of Google API since it is per session basis.





How to use Read More Toggle for dynamic Text


With my Rating Compnent the user can write text about some product. Now when the user writes more than three lines, the component should show only 3 lines and add Read More toggler sothat somebody can read the whole text by clicking on the Read More href. See here How to add Read More Toggler when the text is longer than 3 lines?





image full screen with jquery and css


I am trying to figure out how css3 and jquery works together for image gallery and i am stuck in this sitaution :


I do have a page like this http://ift.tt/1EwSW3N i got right the first part, when i have to load the large image and switch from one to another with this code starting from HTML i have a the thumbnails at the left and the main image to view at the right like this.



<div id="thumbsBox">





<img id="one" src="tn/image-01.jpg" alt="first" class="blurredThumb"/>
<img id="two" src="tn/image-02.jpg" alt="second" />
<img id="three" src="tn/image-03.jpg" alt="third" />
<img id="fourth" src="tn/image-04.jpg" alt="fourth" />

</div>


<div class="largeImage">

<img src="lg/image-01.jpg" alt="first" />


</div>
<p id="fullscreen"> Here full screen</p>


this is the css used



body {

margin: auto;

}


#thumbsBox {

float: left;
margin-top: 300px;
width: 220px;
padding: 0px;

}

#thumbsBox img {

float: left;


}



#largeImage {


width: 900px;
height: 600px;
border: 1px solid #333333;
float: right;
margin-right: 200px;
margin-top: 100px;


}

#largeImage img {
width: 100%;
height: 100%;


}


.blurredThumb {

opacity: 0.7;

}


#thumbsBox img:hover {

float: left;

opacity: 0.7;
}

.fullscreen {

margin: 0px;
width: 100%;
}


and the Jquery



$(document).ready (function(){


$('#thumbsBox img').click (function() {

$("#largeImage img").attr('src', this.src.replace('tn','lg'));



});



$("#fullscreen").click (function() {

$("#thumbsBox").css('display', 'none');

$("#largeImage").addClass('fullscreen');



});


});


I fouind it working as said when i have t ochange the image, but i cannot figure out properly how to make a selected image "full screen" any tips is welcomed.thanks for help in advance


Paolo





Automatic tag autofill like on SoundCloud?


I want to implement the same system of automatic tag recognition in my Node.Js app: a user types in #word1 word2 and this is recognized as one tag with two words, not as only one tag.


I know of jquery.textcomplete and jquery.taghandler but these only can do tags that are one word long. And I need a system that would recognize tags that are phrases, like on SoundCloud:


enter image description here


Do you know any library that would help me do that?


Thanks!





Problems with js Laravel


I have strange problem with java script libraries, what included in my laravel project. My main-page route is http://localhost/MySite/public, my js scripts and JQuery work fine on this page, also everything allright with routes, what look like http://localhost/MySite/public/level1. But scipts don't work on the level2 or more routes. For example: On such route http://localhost/MySite/public/section1/section2 I'am unable to use JQuery and my own scripts.


Does anybody know how to fix this?


Here my reference to js libraries:



{{HTML::script('js/Myscript.js')}}
{{HTML::script('js/JQuery.js')}}


Also I tried a common way with <script> tag - no positive results.





change between divs automatically


i'm trying to create a automatically photo changer in my web. i have a "mother" div that inside it i have another 3 divs(each div has his own id because of each one of them has a different background-image). what i want to do is to change between the "children" divs automatically (i don't care about the type f the animation). any idea how can i do it? here is my code



<div id="main_pics" class="container">
<!-- photos here -->
<div id="main_photo1"></div>
<div id="main_photo2"></div>
<div id="main_photo3"></div>
</div>

#main_pics{
margin-top: 57px;
width: 100%;
height: 500px;
}
#main_photo1{
width: 100%;
height: 500px;
background-image: url("1.jpg");
background-position: center center;
background-size: cover;
}

#main_photo2{
width: 100%;
height: 500px;
background-image: url("2.jpg");
background-position: center center;
background-size: cover;
}

#main_photo3{
width: 100%;
height: 500px;
background-image: url("3.jpg");
background-position: center center;
background-size: cover;
}


tanks!





vendredi 30 janvier 2015

Catching an error response when loading content for a new window javascript


I have an input element which triggers a popup with a rendered pdf. However, generation of this pdf is going to fail under certain conditions. I would like to catch the resultant error in the original window and render the popup only if the request succeeds. This is trivial to do if I make two requests:



$.ajax({
method: 'GET',
url: url,
success: function() {
window.open(url);
},
error: function() {
...
}
});


But, I'd like to avoid that second request since this pdf generation is quite expensive. I've currently tried the following:


Create empty window, write pdf to DOM, pushState().



success: function(r) {
var w = window.open();
w.docuent.write(r);
w.history.pushState('init', 'A PDF!', url);
}


This fails since r contains a PDF bytestring.


Open a window with the bytestring, then pushState().



success: function(r) {
var w = window.open('data:application/pdf,' + escape(r));
w.history.pushState('init', 'A PDF!', domain + url);
}


This fails since the pushState overwrites the initial stream data.


How can I create a new window with the rendered PDF (without using any external library other than jquery) using the response data and then set its url correctly?





Toggle my menu when you click my nav button


What I am trying to achieve is when I click on my <div> class "menu" my <ul> with the class "nav" appears, and when its clicked again, it toggles so that its not visible.


HTML



<div class="menu">
<div class="line"></div>
</div>
<ul class="nav">
<li><a href="#">Home</a></li>
<li><a href="#">Prices</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>


JavaScript



$('line').click(function(){
$('ul.nav').slideToggle();
})




Backbone click event not working correctly in firefox


This code executes perfectly in safari and chrome but has problems with Firefox.


Basically, I have a group of radio buttons. This click event should only be fired if the radio button has an attribute of checked. However for some reason, the radio button in firefox seems to fire the event even when the radio-button is not checked.



var MyView = Backbone.View.extend({

events: {
'click input[type="radio"]:checked' : 'radioListener',
},

radioListener : function(evt) {
var selectedObject = evt.currentTarget;
$(selectedObject).prop('checked', false);
$(selectedObject).val('');
$(selectedObject).change(this.clearSelection(evt));
}

});




Discontigious Selection is not supported error in google chrome and chromium


I am working on a bookmark app where i have to store the user's selected keywords or words or content. I am using the createRange() and addRange() javascript methods to create the range and then find out the selected elements/contents by the user. The code i written for this is as follow.



<head>
<script type="text/javascript">
var storedSelections = [];

function StoreSelection () {
if (window.getSelection) {
var currSelection = window.getSelection ();
for (var i = 0; i < currSelection.rangeCount; i++) {
storedSelections.push (currSelection.getRangeAt (i));
}
currSelection.removeAllRanges ();
} else {
alert ("Your browser does not support this example!");
}
}

function ClearStoredSelections () {
storedSelections.splice (0, storedSelections.length);
}

function ShowStoredSelections () {
if (window.getSelection) {
var currSelection = window.getSelection ();
currSelection.removeAllRanges ();
for (var i = 0; i < storedSelections.length; i++) {
currSelection.addRange (storedSelections[i]);
}
} else {
alert ("Your browser does not support this example!");
}
}
</script>
</head>
<body>
Select some content on this page and use the buttons below.<br /> <br />
<button onclick="StoreSelection ();">Store the selection</button>
<button onclick="ClearStoredSelections ();">Clear stored selections
</button>
<button onclick="ShowStoredSelections ();">Show stored selections</button>

</body>


This code is working perfectly on Firefox. I am able to select multiple things one by one and able to show the selected content again but on chrome and chromium i am getting Discontiguous selection is not supported. error when i store more than one elements in range array and click on show stored selections button.


Help will be appreciated. And please suggest me if there is some other alternatives do accomplish this bookmarking task.






I have developed a polymer element. In this element I receive some parameters. When I pass [value array] parameter to element does not work. But if I put the values manually, it works.


This is the polymer element head:



<polymer-element name="nick-viewer-card" attributes="program details link chart">


This is the code problem:



<div class="heading" on-click="{{ toggle }}">{{ program }}</div>
<core-collapse id="collapse">
<div class="content">
<div>{{ details }}</div>
<div><a href="{{ link }}"> more details</a></div>
<div>{{ chart }}</div>
<chart-pie
width="150"
height="150"
values="[30, 50, 100, 40, 120]"> <!-- {{ chart }} -->
</chart-pie>
</div>
</core-collapse>


And this is the invocation:



<nick-viewer-card program="{{gsx$program.$t}}" details="{{gsx$details.$t}}"
link="{{gsx$link.$t}}" chart="{{gsx$chart.$t}}"></nick-viewer-card>


I included #mudasobwa suggestiong:



<div>{{ chart }}</div>
<div><a href="{{ link }}"> more details</a></div>
<chart-pie
width="150"
height="150"
values="{{ chart }}">
</chart-pie>


This is the output:


enter image description here


and the console error is related the type: enter image description here





How to calculate number of characters of monospace font that fit into div


I have code like this:



div {
font-family: monospace;
font-size: 12px;
line-height: 14px;
}

$(function() {
var div = $('div');
var space = $('<span>&nbsp;</span>').appendTo(div);
var num_chars = div.width() / space.width();
var chars = '';
for (var i=0; i<num_chars; ++i) {
chars += 'd';
}
div.html(chars);
space.remove();
});


but number of characters is way to small to fill the width of the div. Anyone know how to calculate the number of characters that will fill one line of a div?





Change the color of a Three.js globe


There is a really cool Three.js demo which has a 3D Globe: http://ift.tt/1nOqFuC


I'd like to change the color of the globe itself from black to navy blue. I'm looking through all the source files and keep changing things but nothing is having an effect on the globe color.


I don't know Three.js or WebGL that well. Might someone help?





Adding additional fields to document before response


I have a request that I respond to as such:



function getstuff(req, res) {
var url = require('url').parse(req.url, true).query.u;

Thing.findOne({url: url}, function (err, doc){
doc.newThings = 'some text!';
res.json(doc);
});
}


I'd like to be able to append some additional data to the document before I send it along to the client. The method I've tried above doesn't seem to be working. Is there clean way to accomplish this?





Moment.js Include text in middle of date format


I have a format of "Jan. 27, 2015 at 8:17 AM" that I need to display using moment.js. I'm using the format



moment.format('MMM. D, YYYY at h:mm A z');


Everything works great except for the word "at". How can I get that word to display as a word instead of the "a" in "at" being translated to the "am/pm". Right now using that date format it ends up looking like this: Jan. 27, 2015 amt 8:17 AM. Notice the "amt" instead of "at".


Is there any simple way of getting it to not process the "a" as part of the format? I have already tried splitting the output and manually entering the "at" after the third space but I'd like a cleaner code if possible.





Quick methods Javascript/Jquery/etc to retrieve all aspnet:textbox (input) contained in a form, excluding other elements


I created a 'test Label' or alert to see values of variables (some way to know values of variables like in Matlab?)


How can I change so i can retrieve the correct number of elements as required (and not value '0' or 'all elements' or 'errors')?


Code is this:



var lenform = document.getElementById("ActionInMoveID").length;
var selform = document.getElementById("ActionInMoveID");

var count = 0;
for (var k = 0; k < lenform; k++)
{
if (selform.elements[k].tagName == "input")
count++;
}
alert(count);


Thanks a lot





What free JS library similar to PeerCDN I can use? [on hold]


PeerCDN was bought by Yahoo, I don't know where to download it or even if it has support on open source version (if there is any), I am looking for some js library implementing the same concept (using WebRTC data channels to deliver static content from browser to browser to reduce to load over main cdn servers)





Javascript closures: Shouldn't this array not be editable via getArray?


Goal 1 is to only allow arr information to be gotten via getArray.

Goal 2 is to only allow arr information to be set via addToArray.



function TestObj(){
var arr = [];

this.getArray = function(){
return arr;
};
this.addToArray = function(val){
arr.push(val);
};
}

var obj = new TestObj();

obj.addToArray('derp');
console.log(obj.getArray());


//['derp']



obj.getArray().push('aderp');

console.log(obj.getArray().length);


// 2


I'm confused. doesn't getArray return a pointer to the array stored in arr, not arr itself? This is closure 101, am I forgetting a () somewhere?





Bootstrap popover works with html but not requested webpage


I am trying to develop a jquery script which will open a popover containing the webpage when you hover over a table td and close it when you move off of it. So far this is working pretty well . The code I have is:



var html = "";
var $that = "";
var $url = "";

$('td').hover(function() {
var contents = $(this).html();

if (contents.match("^http")) {
console.log('contents', contents);
$that = $(this);
$url = contents;

$.ajax({
type: "POST",
url: "/echo/html/",
context: $that,
data: {u: 'http://ift.tt/gbk8l4'},
dataType: 'html',
error: function(jqXHR, textStatus, errorThrown) {
console.log('error');
console.log(jqXHR, textStatus, errorThrown);
}
}).done(function(html) {
console.log(' here is the html ' + html);


html = '<ul class="nav"><li><a href="#">hola</li><li><a href="#">hola2</li></ul>';
$link = $('<a href="myreference.html" class="p1" data-html="true" data-bind="popover">');
$link.data('content', html);
$(this).html($link);

$that = $(this);

// Trigger the popover to open
$link = $(this).find('a');
$link.popover("show");

})
};
}, function() {
console.log('this2 ', $that);
$link = $that.find('a');
console.log('$link2 ', $link);
$link.popover("hide");
$that.html($url);
});


and you can see it at:


JSFiddle


The problem arises over inserting a webpage into the popover via an ajax request. You can see what happens if you remove the line:



html = '<ul class="nav"><li><a href="#">hola</li><li><a href="#">hola2</li></ul>';


It no longer works. What am I doing wrong and is it possible to load a full webpage into a popover given all the unpredictable js within in?





chrome.webrequest.onBeforeSendHeaders never called



chrome.webRequest.onBeforeSendHeaders.addListener(function (req) {
console.log("hello");
debugger;
});


I have this in my background page of my extension, and the callback function is never called. Why?





Data annotation into JSON?


I'm working on an AJAX data grid for MVC 4 web aplication and will be receiving data as a JSON result from the controller. So I'll be serializing the C# model object into javascript.


I need to mark some of the attributes as sortable and thought it'd be cool to use the Data Annotation. Of course there's no such thing in javascript, so that data would be lost after the serialization process. Is there any way to populate those attributes into JSON?


Regards


Lukasz





Making ColdFusion vars available to javascript functions


I'm trying to implement some Bootstrap widgets with a ColdFusion site to make a dashboard style page for an intranet application. Being a JS newbie, I've figured out some of the simpler ones, but a couple are over my head.



** mainpage.cfm**
<insert all css links here>
<cfinclude template="myQueries.cfm"> **gets the data**

Body of Page here
<h4 class="value"><span>215</span><span>$</span></h4> **this span grabs the data from the .js file

<!--LOADING SCRIPTS FOR PAGE-->
<script src="js/main.js"></script>
<script src="js/index.js"></script>


From what I can tell is the '215' is a default if the span data is not returned.


And the code snippet from the index.js file:



$(function () {

//BEGIN COUNTER FOR SUMMARY BOX
counterNum($(".profit h4 span:first-child"), 189, 112, 1, 30); ** these are just included sample data
counterNum($(".income h4 span:first-child"), 636, 812, 1, 50);
counterNum($(".task h4 span:first-child"), 103, 155 , 1, 100);
counterNum($(".visit h4 span:first-child"), 310, 376, 1, 500);

function counterNum(obj, start, end, step, duration) {
$(obj).html(start);
setInterval(function(){
var val = Number($(obj).html());
if (val < end) {
$(obj).html(val+step);
} else {
clearInterval();
}
},duration);
}
//END COUNTER FOR SUMMARY BOX
});


I have CF vars from my cfqueries to pass to each of the 4 parameters for each line.


I have tried other solutions, such as to cfinclude the index.js instead of and also tried just to rename it to a .cfm and cfinclude it.


I thought the best way was just to set my cfvars to match the required ls vars, but I can not get the syntax right for each of 4 levels of the 4 parms.


I have a lot of this type of integration to do and want to get it right the first time before doing the whole site, especially concerning the best way to integrate CF with JS. Any Best-Way advice would be appreciated.