jeudi 26 mars 2015

Error in query: Invalid JSON string when Creating a Chart from a Spreadsheet? GAS


Why am I getting the error Error in query: Invalid JSON string when attempting to create a chart from a spreadsheet using the Google example script from their documentation here?


I can't figure it out. The only thing that I changed is the spreadsheet URL. The rest is directly from the documentation example. I provided all of my code below. Any help you guys could give would be greatly appreciated. Thanks, Brandon





function doGet() {
return HtmlService.createTemplateFromFile('index')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
};

function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
};






<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://ift.tt/JuZcy0"></script>
<script type="text/javascript">

// Load the Visualization API and the controls package.
google.load("visualization", '1', {packages:['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query(
'http://ift.tt/1M0dNkF');
query.send(handleQueryResponse);
}

function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}

var data = response.getDataTable();
var chart = new google.visualization.ColumnChart(document.getElementById('columnchart'));
chart.draw(data, { legend: { position: 'none' } });
}
</script>

<title>Data from a Spreadsheet</title>
</head>

<body>
<span id='columnchart'></span>
</body>
</html>






<div id="EntireSite">

<div>
<?!= include('Chart'); ?>
</div>



enter image description here



ng-click to call a function in services for logging ratings onto firebase


I am creating a website which logs user ratings to firebase, but I cannot accomplish the calling of a services.js function which is meant to log the user's rating on click of one of stars 1-5. Is there something wrong with my code, or something I am missing? Here is a snippet of the services.js, controllers.js, as well as the ratings div from the html. Any help is much appreciated!


From the services.js



angular.module('dev.services', [])
.factory('ratingsService', function() {
return {
//removed return envelope
//var obj = {};
/**
* @todo Add a check to determine whether or not the specified user has already rated the specified item.
*
* @param {String} userId
* @param {String} itemType
* @param {String} itemId
* @param {Number} rating
*/
rate: function(userId, itemType, itemId, rating) {
// @todo Construct a new promise that resolves when both Firebase operations have been performed.
$firebase( new Firebase(dvUrl + '/users/' + userId + '/ratings/' + itemType + '/' + itemId) ).$set(rating);
$firebase( new Firebase(dvUrl + '/' + itemType + '/' + itemId + '/ratings/' + userId) ).$set(rating);
console.log("SUCCESS!");
},
/**
* @param {Object} ratings
* @returns {Number} avgRating
*/
getAvgRating: function(ratings) {
var ratingsTotal = 0;
var ratingsCount = this.getRatingsCount(ratings);

if(ratingsCount === 0) {
return 0;
} else {
for(var rating in ratings) {
if( ratings.hasOwnProperty(rating) ) {
ratingsTotal += parseFloat(ratings[rating]);
}
}

return (ratingsTotal / ratingsCount).toFixed(1);
}
},
/**
* @param {Object} ratings
* @returns {Number} ratingsCount
*/
getRatingsCount: function(ratings) {
return ratings == null
? 0
: Object.keys(ratings).length;
}
//removed return envelope
//return obj;
}
})


From the controllers.js



angular.module('DeViine.controllers', [])
.controller('rateCtrl', ['$scope', 'ratingsService', 'dvUrl', function($scope, ratingsService) {
$scope.rate = function (item, rating) {
ratingsService.rate(userId, item.type, item.id, rating);
}
}]);


From the HTML



<div class="ratings">
<div ng-click="rate(itemId, 1)" class="rate rate1" title="1"></div>
<div ng-click="rate(itemId, 2)" class="rate rate2" title="2"></div>
<div ng-click="rate(itemId, 3)" class="rate rate3" title="3"></div>
<div ng-click="rate(itemId, 4)" class="rate rate4" title="4"></div>
<div ng-click="rate(itemId, 5)" class="rate rate5" title="5"></div>
</div>




Knockoutjs - Template with dynamic variables


I'm learning javascript and ko by trying my hand at a character sheet for my favorite tabletop rpg. Since this is day 3, I'm not even sure I'm approaching this correctly, but below is my attempt at producing a form for skills. It produces no errors, but also has zero functionality.


The evals are my attempt to produce a reference to other observables/computed observables, but no luck. The $data part of the eval was a later addition of an interpretation of advice on how to correct the problem.



<script type="text/html" id="skills-template">
<div data-bind="template: { name: 'skills-template', foreach: skills }"></div>
<div class="row">
<div class="col-md-1" data-bind="text: skill"></div>
<div class="col-md-1"><strong data-bind="text: eval('$data.' + skill + 'Total')"></strong></div>
<div class="col-md-1"><input size="2" data-bind="textInput: eval('$data.' + skill + 'Ranks')" /></div>
<div class="col-md-1"><strong data-bind="text: eval('$data.' + skillMod)"></strong></div>
<div class="col-md-1"><input size="2" data-bind="textInput: eval('$data.' + skill + 'Mod')" /></div>
<div class="col-md-1"><strong data-bind="text: untrained"></strong></div>
<div class="col-md-1"><strong>&nbsp;</strong></div>
<div class="col-md-1"><strong>&nbsp;</strong></div>
<div class="col-md-4">&nbsp;</div>
</div>

</script>


For reference, here is the skills obj I created.



self.skills = [
{ skill: 'Acrobatics', skillMod: 'dexMod', untrained: 'Yes', acPenalty: 'Yes' },
{ skill: 'Appraise', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'No' },
{ skill: 'Bluff', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'No' },
{ skill: 'Climb', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'Yes' },
{ skill: 'Craft', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'No' },
{ skill: 'Diplomacy', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'No' }
]


And this is an example of a computed observable I tried.



self.AcrobaticsTotal = ko.computed(function() {
return Number(self.AcrobaticsRanks()) + Number(self.dexMod()) + Number(self.AcrobaticsMod()) + Number(self.AcrobaticsTrained());
}, this);


I can get this all working if I hand code it, but I thought I would do it smartly and avoid typing all 40 skills and all of the associated observables. Thanks for any advice.


edit: I should have been more clear, I'm trying to get the data-bind to be the equivalent of other observables that I've declared. I want eval($data.' + skill + 'Total') to be acrobaticsTotal and have ko act on the acrobaticsTotal observable.





Will this code ever return false?


I'm reviewing some code where the logic looks flawed. I'm not sure if the following code will ever return false because of the if else return flow. My question is, will the following code ever return false, or even throw an error?



function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
var select = document.getElementById("selectmenusearch");
var selected = select.options[select.selectedIndex].value;
if(selected === 'organisation') {
submitSearchForm('<%= doOrganisationSearchURL %>');
} else {
submitSearchForm('<%= doIndividualSearchURL %>');
}
} else {
return false;
}
return true;
}


So the flow to me looks like



if (this condition is true) {
//execute some code
} else {
return false
}
else return true


NB: I know it would be better to refactor to have only one return statement but it looks to me like there are two else statements.





Backbone save() respond with success


I have a properly configured Backbone Model, but when I run the save method like so:



backbone_model.save(null, {

success: function () { console.log('ok'); },

error : function () { console.log('not ok'); }

});


I have a successful POST request sent (and Backbone request is triggered) to my Node instance which responds with nothing except 200 OK like so:



app.post('/backbone', function (req, res) {
res.send(); // Automatically sends 200 OK
}


But Backbone does not trigger the sync event, and the error callback is executed. I've also tried returning 201 Created, with no success.





Angular: When does app.config get called?


I am creating a chrome extension UI using angular. I want to make it so when the user clicks the icon in the upper right the correct screen appears. If the user is not logged in they should go to the login page. If the user is logged in and in drawing mode then they should go to the drawing screen, if they are logged in and not drawing then they should go to the main menu.


My main problem is checking whether or not they are already in drawing mode. I am sending a message to my content scripts to check whether or not I am in drawing mode, but for some reason this callback is never getting called! Very disappointing. I'm not sure when code in app.config gets called; when does it?


app.js



app.config(function($stateProvider, $urlRouterProvider) {
var rootRef = new Firebase(mysterious_url);
var user = rootRef.getAuth();
chrome.tabs.sendMessage('isInDrawingMode', {action: 'isInDrawingMode'}, function(response) {
if (!user) {
$urlRouterProvider.otherwise('/login');
} else if (response.inDrawingMode) {
$urlRouterProvider.otherwise('/draw');
} else {
$urlRouterProvider.otherwise('/main');
}
});


contentscripts.js



chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse){
// Toggle User Canvas Messages
if ( request.toggle === 'off' ){
// toggleUserCanvasOff();
disableDrawingMode();
sendResponse({confirm:'canvas turned off'});
} else if ( request.toggle === 'on' ){
enableDrawingMode();
// toggleUserCanvasOn();
sendResponse({confirm:'canvas turned on'});

// Initialize toggle status for popup button
} else if ( request.getStatus === true ){
sendResponse({status:toggle});
} else if (request.canvasData) { // new Canvas data
onCanvasData(request.site, request.user, request.data);
} else if (request.erase){
eraseUserCanvas();
} else if (request.changeColor){
lineColor = request.changeColor;
} else if (request.image){
getCurrentUser(function(user){
var userCanvas = $('.'+ user);
addOneTimeClickEvent(userCanvas, addImage, request.image);
});
} else if (request.action) {
sendResponse({inDrawingMode: "true"});
}
}
);




How to change css styling for different lines within a paragraph in javascript


So I have this code that defined a variable called circle, and appended it a title. The title has four lines, first is the country, second is the price, 3rd is the value, and 4th is the gdppc. Now I want to make the gdppc a larger font size than the previous 3 variables. This would require me to style gdppc separately from the others (currently they are all styled by this css called tipsy). However, I don't know how exactly would I do that.



circles.append("title")
.text(function(d) { return d.country + "<br/> " + "Price=" + d.trust
+ ", Value=" + d.business + "<br/> " + d.gdppc; });

$(".circles").tipsy({ gravity:'nw', html: true,});


The idea is probably to make gdppc a separate variable, and style it separately.





Javascript Alert box popup


I have a very simple question. I'm a beginner at Javascript. I was wondering what is the correct method to write a Javascript alert box? Is it along the lines of {alert}?





Are there any triggers for file imports done using browser?


I was under the assumption that the afterSave() or beforeSave() triggers will fire for every new row (object) created when I import a CSV file using the browser. Unfortunately, this doesn't seem to be the case.



So, are there any triggers available for processing newly created objects (rows) when importing files via browser?





Text Duplicating in Meteor?


I'm attempting to make a Meteor app which allows multiple people to edit a body of text concurrently (think Google Docs/Drive).


I figure in order to do this, I need to have a template which just shows the text that's currently in the database, and then whenever the text is modified, it needs to update the text in the database.


I was able to reproduce the same problems from my full app in this minimal reproduction below (designed to be used by a single user instead of multiple, thus swapped from using a Mongo Collection to a Session.)



<body>
{{> hello}}
</body>

<template name="hello">
<pre contentEditable="true">{{text}}</pre>
</template>


(The exact same problem happens if I use a div instead of a pre.)



if (Meteor.isClient) {
Session.setDefault('text', "Edit me!");

Template.hello.helpers({
text: function () {
return Session.get('text');
}
});

Template.hello.events({
"input pre": function (event) {
Session.set('text', $(event.target).text());
}
});
}


Try typing a bit in the application and the bug should pretty quickly be apparent to you: with each keystroke it takes all of the existing text and appends it to what you've typed (so with each keystroke, it duplicates all the text). Here's the really weird part: this behavior doesn't always start immediately... in fact, I haven't found any particularly reliable ways of reproducing it. Once it has duplicated the text a single time, it'll reliably do it again and again with each keystroke, up until you refresh the page. After you refresh the page, sometimes the bug appears again with your next keystroke, other times it can take ~20 keystrokes before it appears.


I've tested this on Safari 8 (both OS X and iOS), Chrome (both OS X and Windows), and Firefox (just OS X) and the issue appears in every browser.


If you haven't been able to reproduce it yet, try highlighting all the text, deleting it, and typing. Also try starting a new line. I find those actions seem to have a higher probability of starting the text duplication, but even those don't consistently start the issue.


My questions are:



  1. Why is this bug occurring?

  2. How can I stop it from occurring?


If you'd like to see the problem first hand without having to run a meteor server (although I gave you everything you all the code already...) I threw it up here.





How to force client reload after deployment?


I'm using the MEAN stack (mongo, express, angular and node). I'm deploying relatively frequently to production...every couple of days. My concern is that I'm changing the client side code and the API at times and I would rather not have to ensure backwards compatibility of the API with previous versions of the client code.


In such a scenario, what is the most effective way of ensuring that all clients reload when I push to production? I have seen that Evernote for example has a pop-up that says something along the lines of please reload your browser for the latest version of Evernote. I would like to do something similiar...do I need to go down the path of socket.io or sock.js or am I missing something simple and there is a simpler way to achieve this?





Anonymous define() module in library's dependencies causes breakage for library's dependents


I'm working on a library that is used in a number of web applications. The library itself does not use RequireJS - it's written in node, and then bundled with browserify - however, some of its dependents are using a RequireJS shim to include the library.


What we've found is that the RequireJS shim used by our dependents breaks with an "mismatched anonymous define()" error, if our library depends on a library that includes an anonymous define module, such as this one from the lodash source:



// Define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module.
define(function() {
return _;
});


I've found the RequireJS documentation on this problem; but all of its solutions seem to be with the assumption that the library importing the library with the anonymous module is using RequireJS, which isn't the case here.


How can I deal with this so that the downstream libraries don't need to do any special handling in order to require our library? Ideally, it'd be nice if we don't have to add custom logic for every library that we use with an anonymous module definition in it, too.





update on change by ajax in yii gridview


I've got a simple table tbl_task in my database with the followings attributes:



  • id int auto_increment

  • description varchar

  • complete boolean


Now I created a gridview. the value of the complete attribute is shown by a checkbox. There should be the possibility to change the value of the complete attribute. If you do that, it should save the changes in the database. Meanwhile the gridview gets every 3 seconds the newest records from the database.


I've tried to adapt the gridview js file but it doesn't work.


Does anyone has an idea how to solve my problem?


Many thanks in advance.





Increase hit area of mouseover in google maps polyline


I have a javascript code using google maps api with many polylines with stroke width 1. I want to add a tooltip, so I am using info window on mouse over. But the problem is, it is really hard to mouseover event for 1 width of polyline. Is it possible to increase the hit area without increasing the polyline width?


It might be a duplicate of How to increase mouseover “hit area” in polyline geomap but the accepted answer there doesn't seem to be good since it suggests to increase the stroke width which I don't want to do.


(I also needed similar thing for mouse click also, I currently find out the nearest marker for this by iterating and finding distance. If a easier solution exists for click also, I'd appreciate that also)





How can I add a class to the selected element on click event with select2?


We are using Select2 version 4.0.0-rc2


To improve mobile usage we would like to implement adding a class to the clicked item in the drop down.


I tried reacting to the select2 events like this:



element.select2({}).on('select2:open', function(){
this.addClass('my-class');
}


However, the problem with this is that 'this' is the option and not the rendered select li. I believe 'this' is because Select2 delegates/passes the event down to the select option.


I also tried directly targeting the result item like this:



$('.select2-results li ["aria-selected=true"]').on('click', function(){
this.addClass('my-class');
}


But I get the same problem as above. 'This' and even Event.target are option.


I found some suggestions from older versions of select2 and tried this:



element.select2({}).on('select2:open', function(e){
$('.search-results li [aria-selected=true]').on('mouseup', function(e){
e.stopPropagation();
this.addClass('my-class');
}


This one only seemed to work on the second click. So, I clicked to open the list, I select an item, nothing happens, I select another item, it then gets the class.



  • Note: Some of the selectors above may not be accurate but its just to give an example. All of my code worked except that I couldnt get my event to fire on the right element.


Could anyone suggest a fix?


Alternatively, on the Select2 page (http://ift.tt/1yf24TR) , they suggest that in version 4 you can write plugins using an adapter. Im not familiar with adapters and can only assume they mean the adapter pattern? I dont understand how I would even start with this. I understand the concept, I write a wrapper so that my functions are called and I can modify them and also pass through to the library methods? If anyone could provide any further info on how I could do that, it would be greatly appreciated.





Switching between flash and iframe version of live streaming Ustream with javascript in wordpress


I'm tryng to make a button for switching between flash version and iframe version of a ustream live channel that i have embed in my personal site


flash code:



<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="640" height="392" id="utv786564"><param name="flashvars" value="autoplay=false&amp;brand=embed&amp;cid=3064708"/><param name="allowfullscreen" value="true"/><param name="allowscriptaccess" value="always"/><param name="movie" value="http://www.ustream.tv/flash/viewer.swf"/><embed flashvars="autoplay=false&amp;brand=embed&amp;cid=3064708" width="640" height="392" allowfullscreen="true" allowscriptaccess="always" id="utv786564" name="utv_n_665786" src="http://www.ustream.tv/flash/viewer.swf" type="application/x-shockwave-flash" /></object>


iframe code:



<iframe width="640" height="392" src="http://ift.tt/1Hy5IR6" scrolling="no" frameborder="0" style="border: 0px none transparent;"> </iframe>
<br /><a href="http://www.ustream.tv" style="font-size: 12px; line-height: 20px; font-weight: normal; text-align: left;" target="_blank">Broadcast live streaming video on Ustream</a>


For this scope i'm using following code:


javascript:



var newHTML = 'html2';
var oldHTML = document.getElementById('divtabone').innerHTML;

function changeText3(){
var currentHTML = document.getElementById('divtabone').innerHTML;
if (currentHTML!=newHTML)
{
document.getElementById('divtabone').innerHTML = newHTML;
}
else
{
document.getElementById('divtabone').innerHTML = oldHTML;
}
}


html:



<div id='divtabone'>html1</div>
<input type='button' onclick='changeText3()' value='change Html'/>


replacing html1 and html2 with flash and iframe code reported above


working demo:


http://ift.tt/1BgU3Pq


I have inserted this code in my test site wordpress:


http://ift.tt/1xv86VC


but how can see when i click change html button i can change video from flash version to iframe version one time only because if i reclick and i want return to flash version it remain in iframe version i have made a demo with codes here:


http://ift.tt/1BgU6dW


the code that i have inserted in functions.php file of wordpress is following:



function mia_on_load_script()
{
// Not our page, do nothing
if( !is_page( 'test' ) )
return;
?>

<script type="text/javascript">
var newHTML = '<div id="1" style="margin-left: 0px; padding: 0px; float: left; width: 640px; height: 392px; border: 0px;"><iframe width="640" height="392" src="http://ift.tt/1Hy5IR6" scrolling="no" frameborder="0" style="border: 0px none transparent;"></iframe></div><div id="2" style="margin-left: 0px; padding: 0px; float: left; width: 320px; height: 392px; border: 0px;"><iframe style="border: 0 none transparent;" src="//www.ustream.tv/socialstream/3064708" width="320" height="392" frameborder="no"></iframe></div>';
var oldHTML = document.getElementById('divtabone').innerHTML;

function changeText3(){
var currentHTML = document.getElementById('divtabone').innerHTML;
if (currentHTML!=newHTML)
{
document.getElementById('divtabone').innerHTML = newHTML;
}
else
{
document.getElementById('divtabone').innerHTML = oldHTML;
}
}
</script>


<?php
};
add_action( 'wp_head', 'mia_on_load_script' );

?>


html in page http://ift.tt/1xv86VC :



<div id="divtabone"><div id="1" style="margin-left: 0px; padding: 0px; float: left; width: 640px; height: 392px; border: 0px;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="640" height="360" id="utv786564"><param name="flashvars" value="autoplay=false&amp;brand=embed&amp;cid=3064708"/><param name="allowfullscreen" value="true"/><param name="allowscriptaccess" value="always"/><param name="movie" value="http://www.ustream.tv/flash/viewer.swf"/><embed flashvars="autoplay=false&amp;brand=embed&amp;cid=3064708" width="640" height="360" allowfullscreen="true" allowscriptaccess="always" id="utv786564" name="utv_n_665786" src="http://www.ustream.tv/flash/viewer.swf" type="application/x-shockwave-flash" /></object></div> <div id="2" style="margin-left: 0px; padding: 0px; float: left; width: 320px; height: 392px; border: 0px;"><iframe style="border: 0 none transparent;" src="//www.ustream.tv/socialstream/3064708" width="320" height="392" frameborder="no"></iframe></div></div>
<input type='button' onclick='changeText3()' value='click to change'/>


Why in wordpress don't work ? Cold be a problem of caching? Any other solution to resolve problem? thanks





uncaught exception: out of memory in Ajax Process


I got a problem I am submitting a simple form that has a small data and when I checked in the console tab the URL of ajax seems to be working but after the ajax is success it is redirected to my homepage and from the console tab I have this weird error:



uncaught exception: out of memory


In my ajax I have this simple code only:



$("#add-comment").on('click', function() {

var id = $('input[name=\'review_id\']').val();
var customer_id = $('input[name=\'customer_id\']').val();
var $comment = $('textarea[name=\'user_comment\']').val();

var sample = "test";

$.ajax({
url: 'index.php?route=product/product/writeSubComment',
type: 'post',
dataType: 'json',
data: { text: sample },
beforeSend: function() {

},
success: function(data) {
console.log(data.test);
},
error: function() {
alert('ERROR!!!');
}
});

});


In my PHP controller I have this function



public function writeSubComment() {

$json = array();

$json['test'] = $this->request->post['sample'];

$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));

}




How can I send a response that is a block of code in a node request response function?


I am trying to have a server side function return a block of code. For example, I want to send the following back after a request:



$('body').css('background-color', 'blue')


What I did was wrap this in quotes and have the following response:



res.end("$('body').css('background-color', 'blue')");


However, as I write many lines code, I want to be able to write it without quotation marks. How can I store many lines of code in one variable perhaps so that I can write res.end(codesnippet)?





$cookies service equivalent to chrome.cookies?


I'm new to angular and am working on trying to rebuild a chrome extension into a generic webapp using angular just to learn it.


One of the very first things the extension does is grab a specific cookie (created by logging into a website in a browser tab) using the command chrome.cookies.getAll(). Is the angular equivalent to this just using the $cookies service with $cookies.getAll()? It doesn't seem to be having the same effect when I test it, which is why I ask, so I apologize if this is a stupid question. Anyway, any guidance is appreciated!





Updating template when route model changes (?)



import Ember from 'ember';

export default Ember.Route.extend({
logMore: 20,
dateEncode: "",
model: function(){
var url = "https://xxxx/api/xxxx";
var localData = JSON.parse(localStorage.getItem("user"));
var data = { auth_token: localData.user_token };

( this.get('dateEncode') !== "" )? url += "?from="+ this.get('dateEncode') : url;
return Ember.$.ajax({
url: url,
headers: { "X-Api-Token": data.auth_token }
}).then(function(data) {
console.log(data);
return data;
});
}.observes('dateEncode'),
actions: {
loadMore: function(){
var today = new Date();
today.setDate(today.getDate() - this.get('logMore'));
var initial = this.get('logMore') + 10;
this.set('logMore', initial);
this.set('dateEncode', today.toISOString());
}
}
});


I am using ajax to call an API and made an action than change the url with a param 'from' it's a date return some days ago, the modal can call and return the new data but the template no change, i don't know how to do it, if there somebody who can help thanks for your time.


Maybe another way to do that (?)





Using Mysql to do multiple INSERT in mu tables [duplicate]



This question is an exact duplicate of:




i want to insert customer details in customer as well as bank table using single query at a time


customer (table) cid,cname (field)


bank (table) bid,amount,cid(field)





How can I find the element clicked on inside a jquery handler?


I'm trying to do a specific action on the clicked element if an argument is passed in the on click method in jquery. When I try to access "this" it's referencing the entire window instead of the clicked on element. How would I access the clicked on element in the handler?


Here's the code I'm using:



var myfunction = function(action) {
var content;
var $this = $(this);
if(action === "one") {
$(".output").text("clicked on one");
$this.addClass("one");
}
if(action === "two") {
$(".output").text("clicked on two");
$this.addClass("two");
}
};
$("#button").on("click", function(event) {
myfunction("one");
});

$("#button2").on("click", function(event) {
myfunction("two");
});


I set up an example on jsbin here. Any help would be appreciated.





JavaScript error with eventListener


I'm getting an error which I'm not quite sure what to make of. Anyway, before I go on to that, I found out about Unobtrusive JavaScript, at first I was just going to add an "OnClick" to my HTML but then found out that isn't a very good thing to do.


Anyway, so I did that and turned up with this code which isn't quite finished yet, but I wanted to try it out anyway before I went in and made any other changes.



window.onload = function findSubmitButton(){
var button = document.getElementsByClass("send_info").addEventListener("click", retrieveInputText());
}

function retrieveInputText(){
var inputArray = document.querySelectorAll("#container_id input[type=text]");
var finalArray;
for (var i in inputArray){
if(inputArray[i].type == "text"){
finalArray.push(i);
}
alert("done");
}
}


The error chrome's console gives me is this: Uncaught TypeError: undefined is not a functionfindInputs.js:5 findSubmitButton


There was also something I wanted to know, I want to be able to use this script with any other sort of input form, so instead of directly identifying the button for this page, I used a class identifier, this way, it works with any page. The only way there would be any issues would be if I had two buttons of the sort, as it is right now, any page with that sort of information only has one button for such procedures. I would appreciate if someone helped me out with this, I'm new to JavaScript.





Making horizontal sliding sections?


Here is an example of exactly what I am trying to create.


I've tried to create on my own a page that kind of worked like that with 3 paragraphs. I only want 1 paragraph to be shown at a time and I want the left and right arrows to take me to the previous and next paragraphs respectively.


I'm not exactly sure how to get only one paragraph showing at a time (I put them all in a container, I'm assuming I would have to do something with that), and I don't really know how to begin with the horizontal sliding (I'm assuming I would need to do something with JS).


Here is what I have so far:


HTML:



<body>
<div class="slide_container">
<p id="slide1" class="slide">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
<p id="slide2" class="slide">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
<p id="slide3" class="slide">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
<button id="prev">←</button>
<button id="next">→</button>
</div>
</body>


CSS:



@import url(http://ift.tt/OIiP2w);

.slide_container {
width: 960px;
margin: 0 auto;
font-family: 'Open Sans';
}
#prev, #next {
border: none;
padding: 10px 20px;
background-color: #efefef;
color: #c2c2c2;
transition: background .2s ease-in-out;
}
#prev:hover, #next:hover {
background: #dedede;
cursor: pointer;
}
#prev:focus, #next:focus {
outline: none;
}
#prev {
float: left;
margin-left: 400px;
}
#next {
float: right;
margin-right: 400px;
}


JavaScript:



var prev = document.getElementById('prev');
var next = document.getElementById('next');

prev.addEventListener('click', function() {
// Somehow to go to the previous slide
});

next.addEventListener('click', function() {
// Somehow to go to the next slide
});


Any help would be very appreciated!


EDIT: Here is the jsfiddle if it is any help.





Set IE specific css styles via javascript


I'm trying to set a CSS property, that is specific to IE, via javascript. Something like the following



document.body.style.-ms-content-zooming = "zoom";


or



document.body.style.-ms-scroll-snap-x = "whatever"


But the css property doesn't get set the way shown above (I tried the first line for sure). How could I accomplish the above task, or setting any css starting with a dash (-) for that matter, using javascript?





How to select multiple values selected in a jQuery multiselect box


I am using the jQuery multiselect api to select multiple values in my application,but what i want that,when i click on a button beside that multiselect box all the selected values should be fetched.But i am not able to do that ,Here i am posting my code.



<div class="showFilter" align="right">
<div class="showDate">
<select name="region" id="regionHome">
<option value="MDC">MDC</option>
<option value="LAC">LAC</option>
<option value="BRO/WPB">BRO/WPB</option>
<option value="NOE">NOE</option>
<option value="OTHER">OTHER</option>
</select>
<input id="start-date-client" type="text">
<input id="end-date-client" type="text">
<input type="button" value="Search" onclick="searchByDate()" class="searchButton">
</div>



<script type="text/javascript">

$(document).ready( function() {

$("#regionHome").multiselect();

function searchByDate(){
var multipleValues = "";

$("#regionHome").change(function() {

multipleValues = $("#regionHome option:selected").map(function () {
return $(this).text();

}).get().join('%%%%%');

alert(multipleValues)
});
}


And This is the code from where i am taking reference



<title>jQuery MultiSelect Plugin Tests</title>
<link rel="stylesheet" type="text/css" href="../../jquery.multiselect.css" />
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="http://ift.tt/1d6AYWj" />
<script type="text/javascript" src="http://ift.tt/ShXNZA"></script>
<script type="text/javascript" src="http://ift.tt/1d6AYp1"></script>
<script type="text/javascript" src="../../src/jquery.multiselect.js"> </script>
</head>
<body>

<h1>Form Submission Test</h1>
<p>Testing to ensure the correct values are actually passed when the form is submitted.</p>

<form action="#" method="post" style="margin-top:20px">
<select id="foo" name="foo" multiple="multiple" size="5">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
<option value="option4">Option 4</option>
</select>

<div><input type="submit" value="Submit" /></div>
</form>

<script type="text/javascript">
$("#foo").multiselect();


$("form").bind("submit", function(){
alert( $(this).serialize() );
return false;
});
</script>

</body>


Here they are using the form with the submit button and getting the value but in my application i don't have any form only the div i have to use.How i can achive this??


But my code is not working ,somebody help me to solve this.I want when i will select two values it will come in the alert





How to clear dropdown options value?


Recently i am facing an unknown problems. I am using customized dropdown list in MVC4 and populating data by ajax. It is working fine but problem is, it is not clearing data after successfully sending data to the controller. Here i tried the example..



<select data-placeholder="Select a Brand..." style="width:254px;" name="brand" id="brand">
<option value=""></option>
</select>

$("#brand").select2({
width: 254
});


For clearing drop down list i have tried like this..



$("#brand").val("");


I have search many example refreshing data in drop down list but i failed. Please help me to solve the problem. Here i have shared my long code



<script type="text/javascript">
$(document).ready(function () {

$("#brand").select2({
width: 254
});
$.get('/Settings/Brands/', function (data) {
$.each(data, function (index, c) {
$('#brand').append('<option value="' + c.id + '">' + c.name + '</option>');
});
});


$('#btnAdd').live("click", function () {
if (confirm("Do you want to Save?") == true) {
$.ajax({
cache: false,
async: false,
type: "POST",
url: "/Settings/ItemAdd/",
dataType: "json",
data: adata,
success: function (data) {
alert(data.msg);
$('#list').trigger('reloadGrid');
},
error: function (data) {
alert(data.msg);
$('#list').trigger('reloadGrid');
}
});
}
$("#itemname").val("");
$("#batchNo").val("");
$("#desp").val("");

$("#brand").find("option").val("");
$("#ctg").val("");
$("#supplier").val("");
$("#unittype").val("");
$("#qty").val("");
$("#bprice").val("");
$("#sprice").val("");
$("#Edate").val("");
$("#qlimit").val("");
$("#vat").val("");
$("#icode").val("");
});





});
</script>




JS/CSS Rotated DIVS to meet in the middle of any screen


So I am trying to rotate 2 divs so at 45 degrees, but I need them to meet in the middle.


I have tried everything I can think of to get these divs to meet in the middle of the window but just can get it to work.


Here is a JSfiddle that explains the goal. http://ift.tt/1D3Cl8g


P.S. these must be 2 separate elements so I can animated them individually.


Here is what I have thus far:



<div id="container">
<div class="greenBG"></div>
<div class="blueBG"></div>
</div>


#container {
position: absolute;
z-index: 1;
width: 100%;
height: 100%;
overflow: hidden;
}

.greenBG {
background: green;
position: absolute;
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
}

.blueBG {
background: blue;
position: absolute;
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
}



$(document).ready(function() {
var wH = $(window).height(),
wW = $(window).width(),
offset = wW/2,
diagonal = Math.sqrt(wH*wH + wW*wW),
diagonalMid = diagonal/2;

console.log('wH',wH);
console.log('wW',wW);
console.log('diagonal',diagonal);
console.log('diagonalMid',diagonalMid);
console.log('offset',offset);

$('.greenBG').css({
height: wW + 'px',
width: wW + 'px',
left: '-'+offset+'px',
top: '-'+offset+'px'
});
$('.blueBG').css({
height: wW + 'px',
width: wW + 'px',
right: '-'+offset+'px',
bottom: '-'+offset+'px'
});


});




Displaying sub-data rows inside a row in SlickGrid Table


I've started using SlickGrid and have to implement a kind of functionality where I need to show sub-row inside a parent row of SlickGrid.


Here's the scenario


enter image description here


Here's Asia, Europe is having sub categories in Services Column and these service columns are expandable/collapsible


I'm trying to customize this for first column.


Is any other link/source available to refer to accomplish the feature.





Insanely basic example of how to use xmlHttpRequest?


I am having trouble figuring out how to use the xmlHttpRequest() method and if I saw a very simple example I think I could pick it up with ease. Here is what I am picturing:


-A text area for user input


-A button that calls a javascript function


-A javascript function that uses xmlHttpRequest() to send the value of the text area to a php page


-A php page that uses fwrite() to log the text area value in a .txt document.


Here's some starting code if you'd like:





<html>
<head>
<script type="text/javascript">
function sendText(){
var message = document.getElementById("inputText").value;
var myRequest = new XMLHttpRequest();
// xmlhttprequest() code that I struggle with understanding.
}
</script>
</head>
<body>
<div align="center">
<textarea id"inputText"></textarea>
<br><br>
<button onclick="sendText()">
Send!
</button>
</div>
</body>
</html>






A simpler way to capture multiple variables in javascript regexps


Comming from the perl/python world I was wondering if there is a simpler way to filter out multiple captured variables from regexp in javascript:



#!/usr/bin/env node
var data=[
"DATE: Feb 26,2015",
"hello this should not match"
];

for(var i=0; i<data.length; i++) {
var re = new RegExp('^DATE:\\s(.*),(.*)$');
if(data[i].match(re)) {
//match correctly, but how to get hold of the $1 and $2 ?
}
if(re.exec(data[i])) {
//match correctly, how to get hold of the $1 and $2 ?
}

var ret = '';
if(data[i].match(re) && (ret = data[i].replace(re,'$1|$2'))) {
console.log("line matched:" + data[i]);
console.log("return string:" + ret);
ret = ret.split(/\|/g);
if (typeof ret !== 'undefined') {
console.log("date:" + ret[0], "\nyear:" + ret[1]);
}
else {
console.log("match but unable to parse capturing parentheses");
}
}
}


The last condition works, but you need a temp var and split it, and you need to have a test in front because the replace works on everything.


Output is:



$ ./reg1.js
line matched:DATE: Feb 26,2015
return string:Feb 26|2015
date:Feb 26
year:2015


If I look up: mosdev regexp it says on (x):



The matched substring can be recalled from the resulting array's elements 1, ..., [n] or from the predefined RegExp object's properties $1, ..., $9.



How do I get hold of the RegExp objects' $1 and $2?


Thanks





Index of an element in a filtered jQuery set


So I have been searching for a couple of hours now and I haven't really found a solution yet.


It seems that the jQuery method .index() when calling on an element in a set, does not take the selector into regard.


To clarify, when I have a list of 5 li elements, where element 2, 3 and 4 have the class "foo". When I first filter these items with $('li.foo'), I get a set back with the size of 3 elements big. When I perform the .index() on the first item in the set like so $('li.foo').first().index(), instead of returning 0 (since it's the first item in the set and index starts counting from 0), it actually returns 1 (or in other words, the index for the second item).


Now with the example above it doesn't really seem necessary in my example to use index, but in my code I actually filter the filtered set( $('li.foo').filter('.active') ) to get a single item and then get the index of that item.


The problem it seems is that .index ignores the filters and selectors and I haven't had any luck in $.inArray();


If anyone could shed some light on how to get the index with a sure fire way, I would be super grateful!!





Check user authentification in Open Social gadget from backend


i am writing a gadget for an OpenSocial site (www.graasp.eu). Inside my gadget i open a connection to a server. To be exact a vert.x event bus opens a connection to my Vert.x backend with the help of sockJS.


Now i want to somehow check, if the user, who opens the connection, is succesfully logged in to the opensocial site to permit the connection.


Any idea how i can do that? Can i access the oauth token, send it to my server and ask the opensocial site, if this token is valid?


Thanks in advance.





Basic query about software that can debug facebook code errors, or even fix them


I've a few facebook groups and pages and they all work fine with sharing whatever I want. But on my main page (last 24 hrs) whenever I try to share something all that happens is the share box pops up for a millisecond (no text) and simply vanishes. I've tried it in both chrome and firefox, and on different computers, cleared chaches, the lot; same result. It's a fully public page too, so it's not a security issue I would not think.


At the moment the only way I'm able gt a rough idea whats going on is using googles right cloick > inspect element, or firefox's comparable function, to see whats going on underneath the webpage. I'm not sure what I am looking for though, and presume there are better more bespoke software to debug things like this.


What software or plugins do you need to see what the code is actually doing as it executes? And hopefully highlight hangup points or show me where the issue likely is, because im totally stumped at the moment.


Thanks.





Video displayed in ReactJS component not updating


I'm new to ReactJS (0.13.1), and I've created a component in my app to display HTML5 video.


It seems to work perfectly but only for the first selection. The video that is actually displayed and playing in the page doesn't change when you switch from one video to another (when this.props.video changes).


I can see the <source src='blah.mp4' /> elements update in the Chrome inspector but the actually rendered video in the page doesn't change and keeps playing if it was already. Same thing happens in Safari & Firefox. All the other elements update appropriately as well.


Any ideas?


Anyway my component below:



(function(){
var React = require('react');

var VideoView = React.createClass({

render: function(){
var video = this.props.video;
var title = video.title === ''? video.id : video.title;

var sourceNodes = video.media.map(function(media){
media = 'content/'+media;
return ( <source src={media} /> )
});
var downloadNodes = video.media.map(function(media){
var ext = media.split('.').slice(-1)[0].toUpperCase();
media = 'content/'+media;
return (<li><a className="greybutton" href={media}>{ext}</a></li>)
});

return (

<div className="video-container">
<video title={title} controls width="100%">
{sourceNodes}
</video>
<h3 className="video-title">{title}</h3>
<p>{video.description}</p>
<div className="linkbox">
<span>Downloads:</span>
<ul className="downloadlinks">
{downloadNodes}
</ul>
</div>
</div>

)
}
});
module.exports = VideoView;
})();




mongoose.js Model.remove only works once within a loop


I'm not sure if this is just my noviceness to asynchronous programming or an actual bug, but whenever I put Model.remove in a loop, it will only work on the first time and then not remove anymore.


My goal is to just have one document in the collection after the function is run, so if there is different way to do that, that would great to know as well.


Here is how my code looks:


(part of server.js)



var schema = new mongoose.Schema({
gifs: [String]
});
var Gifs = mongoose.model('Gifs', schema);

setInterval(function(){

request('http://ift.tt/WEPoqB', function(error, response, html) {

if (!error){
var $ = cheerio.load(html);
$('a.title', '#siteTable').each(function(){
var url = $(this).attr('href');
urls.push(url);
});
}

//remove everything in the collection that matched to {}, which is everything
//then in the callback save the document
//currently know that this will in fact remove all documents within the model
//however, it will only work on its first run
Gifs.remove({},function(error){
console.log('removed all documents');
Gifs.create({gifs: urls}, function(error){
console.log("created new document");
});
});

});
}, 60000);




CLNDR.js pass variable into underscore.js


I have created a calendar with CLNDR.js. Everything works very well but I want to pass the selected date into Underscore to show only the events day.


Part of my clndr html:



<div class="events-list">
<% _.each(eventsThisMonth, function(event) { %>

<!--<% if (event.date == selectedDate) { %>-->

<div class="event">
<a href="<%= event.url %>">. <%= event.location %></a>
</div>

<!--<% } %>-->

<% }); %>
</div>


Script:



$(window).load(function(){

$('#mini-clndr').clndr({
template: $('#calendar').html(),
events: events,

clickEvents: {
click: function(target) {
if(target.events.length) {

var selectedDate = target.date['_i'];

var controls = $('#mini-clndr').find('.controls');
var daysContainer = $('#mini-clndr').find('.days-container');
var eventsContainer = $('#mini-clndr').find('.events');

controls.slideUp( "slow" );
daysContainer.slideUp( "slow" );
eventsContainer.slideDown( "slow" );

$('#mini-clndr').find('.x-button').click( function() {
controls.slideDown( "slow" );
daysContainer.slideDown( "slow" );
eventsContainer.slideUp( "slow" );
});

}

}
},

adjacentDaysChangeMonth: false

});
});


Someone can help me? It's the first time I use Underscore.js





Web Service is not called by Ajax


I`m trying to call to Web Service from ajax and get string array in return,but whatever that i do ,i got 404 error in console log.


This is my client code:



$.ajax({
url: "http://localhost:55397/WebService1.asmx/GetList",
cache: false, type: "POST", contentType: "application/json; charset=utf-8",

dataType: 'json',
success: function (data) {
tags = data.d;
},
error: function () { alert("AutoComplete Server not found");}
});


and this is my Web Service code:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using ExpressDeal.Models;
using ExpressDeal.Controllers;
using System.Web.Script.Services;


namespace ExpressDeal
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

public class WebService1 : System.Web.Services.WebService
{
private BaseLogic bl = new BaseLogic();

[WebMethod]
[ System.Web.Script.Services.ScriptMethodAttribute()]
//[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Xml)]
public string [] GetList()
{
return bl.Context.Items.Select(i=>i.Name).ToArray();
}
}
}


Can anyone tell me what wrong with it and how to make it work?





Mobile HTML input textbox hide soft keypad on submit


I have a search text box that onsubmit event will get search results using AJAX. So I am using the same page to refresh/update the search results.


But, on mobile devices with both chrome and safari, the soft-keyboard does not hide on submit event.


How can I hide the soft-keypad for mobile only? (FYI - I tried to force onblur but it affects the desktop layout, im using bootstrap responsive layout)





Upload files to Dropbox using a Dropbox Core API in Javascript


I am working on a simple chrome-extension that needs to upload files to the user's dropbox folder. I am using the simple AJAX requests as mentioned below to upload files, however it works for files with extensions such as .txt, .json, .c, etc i.e. files whose mime type is of type text/plain or similar type but all other file types such as pdfs, image files etc get corrupted and produce blank contents. What am I missing in uploading the files the correct way.



function startUpload()
{
var folderPath = $(this).closest('tr').attr('path')+'/';
var file = $("#upload_file")[0].files[0];
if (!file){
alert ("No file selected to upload.");
return false;
}

var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
uploadFile(folderPath+file.name,evt.target.result,file.size,file.type);
}
}

//function to upload file to folder
function uploadFile(filepath,data,contentLength,contentType){
var url = "http://ift.tt/1NeCQNT"+filepath;
var headers = {
Authorization: 'Bearer ' + getAccessToken(),
contentLength: contentLength,
};
var args = {
url: url,
headers: headers,
crossDomain: true,
crossOrigin: true,
type: 'PUT',
contentType: contentType,
data : data,
dataType: 'json',
success: function(data)
{
getMetadata(filepath.substring(0,filepath.lastIndexOf('/')),createFolderViews);
},
error: function(jqXHR)
{
console.log(jqXHR);
}
};
$.ajax(args);
}




The DOM is not rendering what it should


I have this JS:



function climat(code, isday, hour){
weather = {'113': (isday == "yes" && hour < 4) ? '<i class="sunn"></i>' : '<i class="moonn"></i>' }
return weather[code]
};

function Meteo(d) {
for (h = 1; h < 4; h++) {
alert(climat(meteo[d].hourly[h].weatherCode, meteo[d].hourly[h].isdaytime, h));
$("#meteo"+h).html(climat(meteo[d].hourly[h].weatherCode, meteo[d].hourly[h].isdaytime), h)
}
};


Now, I dont get what it should, I used for this the alert() and the tenary is ok, so what happens?


Here is test from the console:



meteo = JSON.parse(localStorage.getItem('meteo')).data.weather
[Object, Object, Object, Object, Object]
climat(meteo[3].hourly[2].weatherCode, meteo[3].hourly[2].isdaytime, 5)
"<i class="moonn"></i>"
climat(meteo[3].hourly[2].weatherCode, meteo[3].hourly[2].isdaytime, 4)
"<i class="moonn"></i>"
climat(meteo[3].hourly[2].weatherCode, meteo[3].hourly[2].isdaytime, 3)
"<i class="sunn"></i>"


Here is a screenshot, the class called is sunn, but it renders moonn:


enter image description here





KendoUI TreeList not taking Reordering or resizing into account


I have the following definition for my KendoTreeList:



$("#Assets_TreeSection").kendoTreeList({
dataSource: tree_Datasource,
height: 300,
reorderable: true,
columns: [
{ field: "AssetNumber", title: "Asset No" },
{ field: "AssetDescription", title: "Description" },
]
});


The problem is that the reorderable true doesnt seem to take any effect on the tree produced. Any ideas why?





How to make an item clickable when using autocomplete plugin


I am trying to use the autocomplete UI to list all related tickets for the user.


I got the script to run at I would like it. But, I have added a custom header to the list and this caused a problem when the user can't click on the options any more to jump to the page


here is my code



$.widget("custom.autocompleteheader", $.ui.autocomplete, {
_renderMenu: function (ul, items ) {
var self = this;
$.each(items, function (index, item) {
self._renderItem(ul, item);
if (index == 0){
ul.prepend('<li class="header-auto">Tickets that may already have your answer</li>');
}
});
}
});

$("#title").autocompleteheader({
delay: 500,
minLength: 5,
source: function(request, response) {

$.ajax({
type: 'POST',
url: 'ajax/loader-related-tickets.php',
data: {title: request.term},
dataType: 'json',
cache: false,
timeout: 30000,
success: function(data) {
if(!data){
return;
}

var array = $.map(data, function(m) {
return {
label: m.title,
url: 'view_ticket.php?id=' + m.id
};
});
response(array);
}
});

},
focus: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
},
select: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
// navigate to the selected item's url
window.open(ui.item.url);
}
});


so the code works and it display the header and the items but when I click on a item it does not open a new page and I get this in the console



TypeError: s is undefined jquery-ui.min.js:8:9691
TypeError: s is undefined jquery-ui.min.js:8:9691
TypeError: ui.item is undefined create_ticket.js:57:3
TypeError: s is undefined


this code works with no problem, but I don't get a header



$("#title").autocomplete({
delay: 500,
minLength: 5,
source: function(request, response) {

$.ajax({
type: 'POST',
url: 'ajax/loader-related-tickets.php',
data: {title: request.term},
dataType: 'json',
cache: false,
timeout: 30000,
success: function(data) {
if(!data){
return;
}

var array = $.map(data, function(m) {
return {
label: m.title,
url: 'view_ticket.php?id=' + m.id
};
});
response(array);
}
});

},
focus: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
},
select: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
// navigate to the selected item's url
window.open(ui.item.url);
}
});


how can I display the header and also make the item clickable and the target url opens in a new page/tab.





Pagination logic shows incorrect page numbers


I have been trying to resolve this issue and can't seem to fix it and am a little unsure what is wrong - I didn't write the code initially.


The code below is meant to show 20 results per page - that works ok. However there is always an extra page number over and above what there should be. So if there should be page numbers 1 to 5 - there is page numbers one to six and the sixth page has no results. It works fine if there is less than 20 results - just when over multiple pages where the problem appears.


Here's the code:



<script>
var js_array = <?php print json_encode($array);?> ;
//alert(1);
//alert(js_array[0]);
for (i=0; i<20; i++)
{
//alert(js_array[i]);
$('#canvas').append(js_array[i]);
}


var end = document.createElement('div');
end.innerHTML = '<b><?php echo $pagewords; ?></b> ';
//alert(js_array.length/15);
var pages = Math.min(Math.round(js_array.length/15), 10);
for (i=1; i<pages; i++)
{
var span = document.createElement('span');
$(span).attr('id', 'span');
$(span).css('cursor','pointer');
span.innerHTML = i;
$(end).append(span);
$(end).append(' ');

}
$(end).addClass("<?php echo $pageclass; ?>");
$('#main').append(end);

$('span').click(function(){
//alert($(this).html());
var page = $(this).html();
//alert(page);
$('#canvas').empty();
if (page==0)
{
for (i=0; i<20; i++)
{
//alert(js_array[i]);
$('#canvas').append(js_array[i]);
}
}
else
{
for (i=page*20-20; i<page*20; i++)
{
//alert(js_array[i]);
$('#canvas').append(js_array[i]);
}
}


});


Can anyone see a problem with the logic of the above.


Thanks in advance for any help!





Using HTML Canvas + Javascript to optimize and image + reduce filesize


I am making a Chrome extension which automatically takes a screenshot of the visible tab and download a JPG to your filesystem. That all works fine but the images are very large (~400kb for a 1280x720px image) and I want to optimize them (ideally around 40kb).


Here is the code I'm using:



var image = new Image();
image.onload = function() {
var canvas = screenshot.content;
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0);

// save the image
var link = document.createElement('a');
link.download = shotname + ".jpg";
link.href = screenshot.content.toDataURL();
link.click();
screenshot.data = '';
};
image.src = screenshot.data;


How can I optimize the image to reduce quality and filesize? I'd like to play around with different quality options so I can see what an acceptable use-case is.





Hero Carousel not working


I am working on a site: The Element


I am trying to use the Hero Carousel but it does not seem to be working and I can't see whats wrong. I just see the images lined up on top of each other.


This is the code I have right now:



JQUERY

$(document).ready(function(){

var menuBtn = $('img.menu-btn');
nav = $('nav');
post = $('div.post');
searchbtn = $('img.searchbtn');
search = $('div.search-area');

menuBtn.click(function() {
nav.toggleClass('menu-open');
});

searchbtn.click(function() {
search.toggle();
});

post.hover(function() {
$(this).find('a').find('p').fadeIn(250);
},function() {
$(this).find('a').find('p').fadeOut(250);
});

$('.hero-carousel').heroCarousel({
easing: 'easeOutExpo',
css3pieFix: true
});
});


PHP



<?php get_header(); ?>

<div class="hero">
<div class="hero-carousel">
<article>
<img src="http://ift.tt/1skZV9u" >
</article>
<article>
<img src="http://ift.tt/1w2laf5" >
</article>
<article>
<img src="http://ift.tt/1w2laf7" >
</article>
<article>
<img src="http://ift.tt/1skZV9E" >
</article>
</div>
</div>

<div id="main">

<?php if ( function_exists( 'get_wp_parallax_content_slider' ) ) { get_wp_parallax_content_slider(); } ?>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<div <?php post_class() ?> id="post-<?php the_ID(); ?>">

<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?>
<p><?php the_excerpt(); ?></p
</a>
<?php endif; ?>
<a href="<?php the_permalink(); ?>">
<h3><?php the_title(); ?></h3>
</a>

</div>

<?php endwhile; ?>

<?php include (TEMPLATEPATH . '/inc/nav.php' ); ?>

<?php else : ?>

<h2>Not Found</h2>

<?php endif; ?>

</div><!--Main End-->

<?php get_footer(); ?>




Is splicing from the end of array faster than from front in javascript?


In javascript, I want to splice the n elements either from the beginning of the array or the end of the array. Which would be faster or are they equal?





String with new lines stored in a meteor collection


I have some paragraphs entered by users stored in a string in a collection but the string has some rough formatting with new line characters. When I present that same paragraph later after accessing it from the collection, how do I have it retain that formatting? If I have the data object and I just do {{ data_paragraph }} it ignores the newlines and just spits out the string.


Is there a way to retain this formatting better when I reprint the data to the user?


Edit -


Here is some additional information :


The text paragraph I am trying to present formatted is just a textarea input through Autoforms. People might post a paragraph with \n characters but the whole string is getting stored in the collection.


Just as an example I pass the data in through Iron-Router :



SingleParagraphController = BaseController.extend({
template : 'singleParagraphPage',
waitOn : function() {
return Meteor.subscribe('singleParagram', this.params._id);
},
data: function() {
return Paragraphs.findOne({_id : this.params._id});
}
})


And then I want to be able to access the individual paragraph like :



<template name="singleParagraphPage">
<h2> {{ name }} </h2>
<p> {{ paragraph }} </p>
</template>


But it needs to have the same formatting with the new lines when they entered it initially into the text area. The new lines are stored in the string but when I just do it like above its just spits out the string and ignores it.





Saving within nested loops with promises


I want to save an object called singleInfo in a column for qualifying parseObjects as shown below. The code below chooses the right objects to save to but it only saves data intended for the last object to all of the objects. I'm pretty sure it is a problem with how I'm doing the loops. I thought the promises would resolve this. I used a similar promise pattern in the past that provided good results but it's not working this time. I think it has something to do with the nested loops as before I only used this patter on a single loop.



var func = function(){
var promise = Parse.Promise.as();
var array = [];
var pairs = [parseObject, parseObject, parseObject];
var a = pairs.length;
while(a--){
var pair = pairs[a];
var singles = [obj, obj, obj, obj, obj];
var b = singles.length;
while(b--){
var single = singles[b];
if(single.value === pair.get('value')){
var singleInfo = {news: single.news, time: pair.get('time')}
query.get(pair.id, {
success: function (goal){
goal.set('newColumn', singleInfo);
array.push(goal.save())
}
})
}
}
promise.then(function(){
return Parse.Promise.when(array);
}




Javascript result to open a new page in same window


I'm using the code for this roulette on codepen for a personal project: http://ift.tt/1D0SFGF. It's all working fine but I'm trying to have the result of the roulette open a specific page in the same window. I'm not sure to target the result of the roulette. My approach was to set values to each variables and create a function:



function openDestinationResult() {
var $100 = "index.html";
var $200 = "content.html";
...
if ($100 === "$100")
{
document.location.replace("result1.html");
}
else if ($200 === "$200")
{
document.location.replace("result2.html");
}


but this obviously doesn't work. I'm new at using javascript so bear with me!


Thanks for any tips/solutions.


cheers





mercredi 25 mars 2015

Printing JSON properties


I am currently trying to send a user information about a JSON object that I've recieved from an API. An example of the format is



[
{
"lang_code": "eng",
"site_language": "1",
"name": "English"
},
{
"lang_code": "afr",
"site_language": "1",
"name": "Afrikaans"
},
{
"lang_code": "ale",
"site_language": "0",
"name": "Aleut"
},
]


I want to be able to access the lang_code property of every single language and send it. I've tried to use



var languageCodes;
var languageResult = body.lang_code; //body is the result from a request.get({ ... })
for(var codes in languageResult) {
languageCodes = languageResult[codes];
}


Object.keys does nothing, as it just sends 72 numbers to me. Any thoughts?


On a side note, I also want people to be able to type "!langages [my command] eng" for example, and it sends "English". Any way to do that?





How to overwrite behaviour of function in javascript


I am trying to override the behaviour of a javascript function for a website that I am developing. I am new to javascript and I am having a problem figuring this out. I have watched several videos and did some reading and this is what I came up with.



jQuery(document).ready(function ($) {

function displayTab(element) {
alert('here'); // test that I am getting here
var tab = Drupal.quicktabs.tab
// Set tab to active.
$(this).parents('li').siblings().removeClass('active');
$(this).parents('li').addClass('active');

// Hide all tabpages.
tab.container.children().addClass('quicktabs-hide');

if (!tab.tabpage.hasClass("quicktabs-tabpage")) {
tab = new Drupal.quicktabs.tab(element);
}

tab.tabpage.removeClass('quicktabs-hide');
return false;
}

if ($( '#quicktabs-menu_block').length > 0) {
$('#quicktabs-menu_block .quicktabs-tabs li').each(function() {
$('a', this).bind({
mouseenter: function(){
$(this).displayTab($(this));
}
});
});
}
});


This is not working - the function is never called. I am not sure what that is, but obviously I am missing something fundamental. What am I missing?





Angular, get dynamic value of textbox to controller


i fetch from json and set the value to my angular ionic app. my textbox holds the value. but im unable to get the textbox value to controller. this is how i have done it


controller.js



$http.post("http://ift.tt/1FFyvmb).success(function(details){
$scope.mydetails= details;
});


and i set the value to my html page



<form>
<div ng-repeat="data in details|limitTo:1">
<p>{{data.f_name}}</p> <!--displays the value-->
<input type="text" ng-model="v.name" value="{{data.f_name}}"/> <!--empty values-->
<input type="text" ng-model="v.id" value="{{data.id}}"/> <!--empty values-->
<button ng-click="push(v)">
</form>


on form click i dont get the textbox values to my controller, im trying to get the vaules to the controller. it doesnt appear



$scope.push= function (v) {
var push_name = v.name; // empty values
var push_id = v.id; // empty values
}




Where is information about introduced sizzlejs source code?


I've been watching sizzlejs on the source code, but found it uses a lot of regular, a longer code is hard to understand. So,I come here to ask information about this.





Change automatically content of span based from number of rows from mysql using Javascript


I'm trying to create a dynamic number of notification feed on the menu. When there is a new added data in one of my table, it will change the number on the notification bar automatically, without refreshing the page.


Here's the html:



<li>
<a href="categories.php">
Categories
<span class="badge" id="badg"></span>
</a>
</li>


And here is the script that I've used:



$(document).ready(function() {
var arr = <?php include("array.php"); ?>; /* e.g. ["1","2","3"] */
var size = arr.length;
document.getElementById('badg').innerHTML = size;
});


The number of arrays are showing, but doesn't change automatically when there is a new data. It will only change when the page are refreshed by the user.


How can I do it automatically?





Using jQuery to toggle visibility of various divs based on two sets of checkboxes?


I have a large number of divs/articles that contain contact info for a bunch of wilderness guides. I'm trying to toggle the visibility of each div based on two sets of checkboxes - One set for the activity the guide specializes in (fishing, hunting, etc) and one set for the state they're in (Alaska, Colorado, etc).


There's a somewhat similar question here that I've been trying to follow, but I'm something(s).


I've got the "sport" filters working correctly. The "state" filters are not and therefor, they don't work together either.


The end goal is for user to select as many sports and states as they'd like and filter out (hide) the divs that don't match both the sport and states chosen.


Here's the JSFiddle


The quick and dirty HTML:



<div class="sport-wrapper">
<h2>Choose a Sport:</h2>
<ul>
<li><label for="fish"><input type="checkbox" id="fish" name="sport"/>Fly Fishing</label></li>
<li><label for="hunt"><input type="checkbox" id="hunt" name="sport" />Hunting</label></li>
<li><label for="raft"><input type="checkbox" id="raft" name="sport" />Rafting</label></li>
</ul>
</div>
<div class="state-wrapper">
<h2>Choose a State:</h2>
<ul>
<li><label for="AK" class="guide-available"><input type="checkbox" id="AK" name="state"/>Alaska</label></li>
<li><label for="CA" class="guide-available"><input type="checkbox" id="CA" name="state"/>California</label></li>
<li><label for="CO" class="guide-available"><input type="checkbox" id="CO" name="state"/>Colorado</label></li>
</ul>
</div>
<div class="results">
<h2>Available Guides:</h2>
<div data-category="guide ak fish">
<h3>Joe's Alaska Fishing Tours</h3>
</div>
<div data-category="guide ak fish hunt">
<h3>Mike's Alaska Fishing and Hunting Adventures</h3>
</div>
<div data-category="guide co fish raft">
<h3>Jim's Colorado Rafting and Fishing Lodge</h3>
</div>
<div data-category="guide ca raft">
<h3>California Whitewater Rafting</h3>
</div>
</div>


And the current jQuery (that doesn't quite work):



$('.sport-wrapper, .state-wrapper').delegate('input[type=checkbox]', 'change', function () {
var $lis = $('.results > div'),
$checked = $('input:checked');
if ($checked.length) {
var selector = '';
$($checked).each(function (index, element) {
if (selector === '') {
selector += "[data-category~='" + element.id + "']";
} else {
selector += ",[data-category~='" + element.id + "']";
}
});
$lis.hide();
console.log(selector);
$('.results > div').filter(selector).show();
} else {
$lis.show();
}
});




How can you add multiple text shadows for one piece of text in one jquery ".css()"


I'm trying to animate the title of a page on my site, I have made the text 3D with multiple shadows, and I want to change what colour it is on page load.


This is what I have currently:



//Animates section 1 of mainpage title
function tsec1Anim(){
$("#tsec1").css({
"font-family" : "Lucida Console",
"font-weight" : "bold",
"text-align" : "center",
"margin-bottom" : "12px",
"top" : "0px",
"color" : "#0033cc",
"font-size" : "75px",
"text-shadow" : "0px 1px 0px #002eb8",
"text-shadow" : "0px 2px 0px #0029a3",
"text-shadow" : "0px 3px 0px #00248f",
"text-shadow" : "0px 4px 0px #001f7a",
"text-shadow" : "0 5px 0 #001a66",
"text-shadow" : "0 6px 1px rgba(0,0,0,.1)",
"text-shadow" : "0 0 5px rgba(0,0,0,.1)",
"text-shadow" : "0 1px 3px rgba(0,0,0,.4)",
"text-shadow" : "0 3px 5px rgba(0,0,0,.50)",
"text-shadow" : "0 5px 10px rgba(0,0,0,.80)",
"text-shadow" : "0 10px 10px rgba(0,0,0,.60)",
"text-shadow" : "0 20px 20px rgba(0,0,0,.75)",
"margin-top" : "15px"
});
}




Firefox add-on SDK: Run content script in all open pages and any new ones


Let's say I have a simple content script, such as window.alert("Hey there"); console.log("Content script").


I cannot figure out a way in the SDK that will make the script run on each open window and tab and also allow it to run on every new one.


Using tabs, the script will run on all new opened windows and tabs but will ignore those that have already loaded:



require("sdk/tabs").on("ready", function(tab) {
tab.attach({
contentScript: 'window.alert("Hey there");'
});
});


Using pagemod with an include pattern of "*", the script will run only on windows and tabs with a non-blank URL:



require('sdk/page-mod').PageMod({
include: "*",
contentScriptWhen: "ready",
contentScript: 'window.alert("AAAAAAAAA");'
});


I'm probably missing something simple that will allow me to implement this correctly. What is the right way to call a content script on all open and new pages?





Can only sort divs if they do not have many tags in their bodies


I have a list of items that need to sort them. The answer in my previous question partially solved the issue. The items in the code that has some tags in its <div data-sid=xx> tags do not get sorted but as soon as I replace the tags with single <h1> tags it works.


This version of code has some tags as body of its <div data-sid=xxx> tags.


Does not work



<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://ift.tt/1r529cJ">
<script src="http://ift.tt/1qRgvOJ"></script>
<script src="http://ift.tt/1mcJXw6"></script>
</head>
<body>
<div class="container">
<button id="price" data-sort="0">Sort by Price:</button><br>
<button id="name" data-sort="0">Sort by Name:</button><br>

<div id= "row" class="row">
<div id="items" class="col-md-7" style="padding-right: 0; border-right: solid;">
<div class="clist">
<div data-sid=12> <<many tags in its body
<a href="www.example.com?id=1">
<div style="margin-bottom: 2px; text-align: left; background-color: green;">
<div>
Name:
<h1>Demo1</h1>
</div>
<div>Price:12</div>

</div>
</a>
</div>
<div data-sid=13>
<a href="www.example.com?id=2">
<div style="margin-bottom: 2px; text-align: left; background-color: green;">
<div>
Name:
<h1>Demo2</h1>
</div>
<div>Price:13</div>

</div>
</a>
</div>
<div data-sid=1>
<a href="www.example.com?id=3">
<div style="margin-bottom: 2px; text-align: left; background-color: green;">
<div>
Name:
<h1>Demo3</h1>
</div>
<div>Price:1</div>

</div>
</a>
</div>
</div>
</div>

</div>

</div>
<script>
$(document).ready(function(){
$('#price').on('click', function(){
var s = $(this).data('sort'); console.log(s);
if(s === 0){
$(this).data('sort', 1);
$('.clist div').sort(function(a,b){
return a.dataset.sid < b.dataset.sid
}).appendTo('.clist')
}else{
$(this).data('sort', 0);
$('.clist div').sort(function(a,b){
return a.dataset.sid > b.dataset.sid
}).appendTo('.clist')
}
});

$('#name').on('click', function(){
var s = $(this).data('sort'); console.log(s);
if(s === 0){
$(this).data('sort', 1);
$('.clist div').sort(function(a,b){
return a.dataset.name < b.dataset.name
}).appendTo('.clist')
}else{
$(this).data('sort', 0);
$('.clist div').sort(function(a,b){
return a.dataset.name > b.dataset.name
}).appendTo('.clist')
}
});
});
</script>

<footer> </footer>
</body>
</html>


As you can see this code just has single tags in body of its <div data-sid=xx> tags.


Works



<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://ift.tt/1r529cJ">
<script src="http://ift.tt/1qRgvOJ"></script>
<script src="http://ift.tt/1mcJXw6"></script>
</head>
<body>
<div class="container">
<button id="price" data-sort="0">Sort by Price:</button><br>
<button id="name" data-sort="0">Sort by Name:</button><br>

<div id= "row" class="row">
<div id="items" class="col-md-7" style="padding-right: 0; border-right: solid;">
<div class="clist">
<div data-sid=12> <<<< just one tag in its body
<h1>12</h1>
</div>
<div data-sid=13>
<h1>13</h1>
</div>
<div data-sid=1>
<h1>1</h1>
</div>
</div>
</div>

</div>

</div>
<script>
$(document).ready(function(){
$('#price').on('click', function(){
var s = $(this).data('sort'); console.log(s);
if(s === 0){
$(this).data('sort', 1);
$('.clist div').sort(function(a,b){
return a.dataset.sid < b.dataset.sid
}).appendTo('.clist')
}else{
$(this).data('sort', 0);
$('.clist div').sort(function(a,b){
return a.dataset.sid > b.dataset.sid
}).appendTo('.clist')
}
});

$('#name').on('click', function(){
var s = $(this).data('sort'); console.log(s);
if(s === 0){
$(this).data('sort', 1);
$('.clist div').sort(function(a,b){
return a.dataset.name < b.dataset.name
}).appendTo('.clist')
}else{
$(this).data('sort', 0);
$('.clist div').sort(function(a,b){
return a.dataset.name > b.dataset.name
}).appendTo('.clist')
}
});
});
</script>

<footer> </footer>
</body>
</html>