dimanche 30 novembre 2014

javascript random in a loop


I have a loop that generates a random number between 0 and 5 and goes fetch a color in an array.


The first color is always yellow and I cannot figure out why.





var hexColors = new Array("#000000", "#FFFFFF", "#FF0000", "#0000FF", "#00FF00", "#FFFF00");
var nameColors = new Array("White", "Red", "Blue", "Black", "Green", "Yellow");

for (var i = 5; i >= 0; i--) {
var hexColor = randomNum(i);
var nameColor = randomNum(i);
$('td:eq(' + i + ')').css("color", hexColors[hexColor]);
$('td:eq(' + i + ')').html(nameColors[nameColor]);
hexColors.splice($.inArray(hexColors[hexColor], hexColors), 1);
nameColors.splice($.inArray(nameColors[nameColor], nameColors), 1);
}

function randomNum(max) {
return Math.floor(Math.random() * max);
}



<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</table>



I re-factored the loop so that it uses increments instead of i-- and it works but I'd still like to know why it doesn't work the other way around.





JavaScript Language Parsing: Distinguish function expressions and declarations


Say that I am creating a simple JavaScript language parser that is only concerning with parsing functions.


I need to differentiate between function "declarations"/"statements" and function expressions. Because they look practically identical, I figure I need to know the context in which function is used.


I suppose that I can determine a function expression by the preceding token. I am thinking that the following algorithm might work:



  • If token is "function", then

    • If previous token is an operator,

      except for a "closing" operator, like "]", "}", or ")", OR

      if previous token is ":", then

      • Function is an function expression.



    • Else

      • Function is a function declaration.






Can I expect this algorithm to correctly determine if a function is a declaration or an expression? If it has flaws, what should be fixed? Or, if it is not possible to distinguish the forms simply by looking at the previous token, how else could I distinguish the forms with the least amount of effort?


(I am aware that Esprima and co. exist. I want to implement a native parser in a different language.)





Two simultaneous ajax calls - one not running or both callbacks returning same responseText


Ok I want to start by saying that I have checked the other posts I could find on here that were having the same issue I am having but none of them fix my issue, two were down to a simple mistake, and the other was to do with PHP session locking, and I am not using sessions.


Basically I am running two Ajax requests to two different pages and using the separate data in different ways after the main page (calling the requests) has loaded.


In an attempt to simplify the problem I have set up this site here (would have used jsFiddle but it gets all funny with HttpRequests): The calling page | One of the pages being called | The second page being called


The sources of the pages linked above is all the code I am using in my example, nothing more, nothing less. The second ajax call can be turned off in the first link by appending '#off' to the url.


The issue I am seeing in my own private Wamp test server is that both callbacks for the Ajax requests are running but the data passed to the functions is the same where it shouldn't be. Both the first and second callback functions are receiving the responseText from the second call. However, on this web server only the second callback runs, the first one does not run at all unless the second ajaxCall is switched off (#off). There must be some difference between my private server and the online one, but I cant really recreate that. However, there is still an issue and I am guessing that the solution to one will be the solution to both.


Can anyone tell me why this is happening? Am I misunderstanding how HttpRequests work? Or is there just some hole in my code?




EDIT:

Here's the code:



<html>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript" >



function ajaxCall(dest, callBack, data, method, async, returnXML) {
method = typeof method !== 'undefined' ? method : "POST";
async = typeof async !== 'undefined' ? async : true;
returnXML = typeof returnXML !== 'undefined' ? returnXML : false;

var ajax;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
returnXML ? callBack(xmlhttp.responseXML) : callBack(xmlhttp.responseText);
}
}
xmlhttp.open(method , dest, async);
if(method == "POST")
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
data === null ? xmlhttp.send() : xmlhttp.send(data);
}



$(document).ready(function() {


ajaxCall("player.htm", function(html) {
$("#player").html("Player:<br>" + html);
}, null);

if(location.hash != "#off") {
ajaxCall("home.htm", function(html) {
$("#home").html("Home:<br>" + html);
}, null);
}


});


</script>



<style type="text/css">

#wrapper {
width: 215px;

}
#wrapper:after {
content: "";
display:none;
clear: both;
}
#player, #home {
width: 100px;
height: 100px;
border: 1px solid black;
margin-right: 5px;
}
#player {float: left;}
#home {float:right;}


</style>



<div id="wrapper">
<div id="player"></div>
<div id="home"></div>
</div>
</html>


Home.htm:



I am the text from home.htm


Player.htm:



I am the text from player.htm




A couple of things to note:


  1. This example is an extremely simplified version of its original application (the resulting problem is the same so there is no sense in me showing the original example as it is a lot of code. That being said, in the actual application one of the pages being requested is displayed and is, in turn, making AJAX requests so running one of the requests inside of the callback of the other isn't really a solution and it seems to be side stepping the issue, as the function 'ajaxCall' surely shouldn't be mixing up the two request objects.




  2. I have not included the original source because I did not want to make an already long post even longer, it is all available at those links however.




  3. Sorry for the really long post, but I had to explain my problem in detail and I have been racking my brains over this for the past couple of days.




  4. You might need to rightclick->reload the page after adding #off to the url to see the changes.







How to make a Range for Scanner input inside a parameter


// Horspower must have a range from 200 to 700 hp and Weight must have a range from 1000 to 3000 pounds



System.out.print("\n Set horsepower (200 to 700 hp) and weight(1,000 to 3,000 pounds) (putting a space between them) of Race car 1: ");

RaceCar racer1 = new RaceCar(scan.nextDouble(), scan.nextDouble() );


How would you add a range to this?


The original RaceCar() is:



public RaceCar(double hp, double wgt)
{
horsepower = hp;
weight = wgt;
}




foreach char in string


I'm trying to achieve the below Java selection in Javascript, and I'm a little stumped at the moment...


Java:



String input = inputField.getText();

foreach (char c: input.toCharArray){
input = input.replace('a','b');
input = input.replace('b','c');
//and so on...
}
return input;
}


This is what I've tried:



var input = document.getElementById('inputField').value; //input field is textarea

for(var i = 0; i < input.length; i++){
for(input.charAt(i)){
input = input.replace('a','b');
input = input.replace('b','c');
}
}
return input;
}


I've also tried some different variations, such as disregarding the loop entirely and just using replace; however, then the replaces will just fire off sequentially and will not cover the length of long multi spaced strings.


Any help on this would be greatly appreciated. Thanks!





Is it possible to center the input type="time" object's digits while it's not on focus?


I'd like to align the view of the the input type="time" object using Javascript. If you notice, the digits are aligned to the left while the input isn't focused. I've tried calling the object's align methods, also tried to text-align with Javascript, the digits move, but only a little.


Anyone knows a solution to this problem I'm having?





How to add one month to a date here?


I have two date variables. The first one defaults to last friday. Based on this date I'm trying to add a month to it. When I try the following code, it does not seem to work.



var StartDate = new Date()
var DayOfWeek = 5;//friday

StartDate.setDate(StartDate.getDate() + (dayOfWeek - 7 - StartDate.getDay()) % 7);


This does not seem to work.



var EndDate = new Date(StartDate)
EndDate.setDate(EndDate.getMonth() + 7)




Infinite loop in Angular using ng-bind


My get_tracking() function returns an object with the summary property.


I tried a few different ways to make this work but I haven't had any luck. To solve this, I would either like to bind the summary property to the pack object or just have it appear in the table.


In this code I am first pulling all packs from the database and storing in $scope.packs. I would then either like to run the get_tracking() function on each one and have the summary attribute applied to each pack.


Is there a way to run a function on each pack once it is returned from the database? When I try to run function in angular I don't have any luck because the pack objects have not yet been returned.


html:



<tbody>
<tr data-ng-repeat="pack in packs"
data-ng-show="((authentication.user) && (authentication.user._id == pack.user._id))">
<td data-ng-bind="pack.tracking_number"></td>
<td data-ng-bind="pack.description"></td>
<td data-ng-bind="pack.company"></td>
<td data-ng-bind=""></td>
<td data-ng-bind="get_tracking(pack).summary"></td>
<td ng-bind=""></td>
</tr>
</tbody>


JS



$scope.get_tracking = function (packet) {
if (packet){
$http.post('/tracking', packet).success(function(response) {
return response.summary;
}).error(function(response) {
});
}
};




How to make this keyword search work?


I am trying to create keyword search for my meteor webapp. And For the most part it works the problem is it is very slow. In the current form when making a article the user gives it keywords. keyS queries one article with a keyword from the search array(skeywords) at a time from mongodb then gives it a score and the 100 highest scored articles are sent to the user. How could it query all the relevant articles at once?


ps Am I going about this all wrong.


The data coming from the client looks like this.



var keyw = ['java','code','jdk','food','good','cook'];
Meteor.call('keyS',keyw);


the data coming out of 'keyS' looks is a array of article ids.


example


Sarticles = [someid,someid]


server



Meteor.methods({
keyS: function(skeywords) {
article: 'tempid',
var score = {
totalScore: 0
};
var potentials = [];
var badArticles = [];
var i = 0;
while (i < skeywords.length) {
var key = [];
key.push(skeywords[i]);
console.log(key);
if (typeof badarticles == "undefined") {
var theArticle = Articles.findOne({
articlekeywords: {
$in: key
}
});
} else {
var theArticle = Articles.findOne({
$and: [{
articlekeywords: {
$in: key
}
}, {
_id: {
$nin: badArticles
}
}]
});
};
if (typeof theArticle == "undefined") {
console.log("no more articles with that keyword")
i++;
continue
}
score.post = theArticle._id;
console.log(score.article);
score.totalScore = 0;
var points = 0;
var theKeywords = thearticle.keywords;
console.log("score worked");
var points = 0;
for (var a = 0; a < skeywords.length; a++) {
var keynumber = theKeywords.indexOf(skeywords[a]);
if (keynumber > -1) {
points++
} else {
continue
}

};


score.totalScore = points;
console.log(score.totalScore);
if (score.totalScore > 2) {
//limiter on number of posts looked at and number added to potentials
potentials.push({
iD: score.post,
totalScore: score.totalScore
});
var ID = score.article;
badposts.push(score.article);
console.log("added to potential" + ID + "to bad");
} else {
var badId = score.post;
console.log("marked as bad" + badId);
badposts.push(score.post);
}
};
potentials.sort(function(a, b) {
return b.totalScore - a.totalScore
})
for (var b = 0; b < 100; b++) {
if (typeof potentials[b] == "undefined") {
break
};
var ID = potentials[b].iD;
Meteor.users.update({
"_id": this.userId
}, {
"$addToSet": {
"Sarticles": ID
}
});
}
}

});




swap movie for image in mobile with css


Is there a proper way to change from an mp4 movie on normal browsers to an image that renders in mobile browsers? The site loads extremely slow on mobile versions and I think it's because of the movie. So here's my issue.


The following code is in an html file:



<video id="video" width="427" height="366" autoplay loop />
<source id='mp4'src="videos/Weight-Care-Patch-Movie.mp4" type='video/mp4'>
<source id='webm' src="videos/Weight-Care-Patch-Movie.mp4" type='video/webm'>
<source id='ogv' src="videos/Weight-Care-Patch-Movie.mp4" type='video/ogg'>
</video>


And I know using the:



@media (max-width: 800px)


I can get it to do something else, but the question is how can I get it to convert to say a background image - even though the html code has a video tag? What can I do to adjust it?


Any help is appreciated. Thank you.





Save HTML locally with Javascript


I do know that Javascript cannot write data in the filesystem, for security reasons. I have often read that the only way to save data locally with Javascript is cookies or localStorage.


But is it possible, in the very specific case when the file is accessed locally (and not through internet) to write data locally ? (without any server language, and even without any server at all... just local browsing of a HTML file)


For example, would it be possible, by clicking on SAVE here on this page ...


...that the HTML file is overwritten with its new content ? (i.e. the local HTML file should be updated when SAVE is pressed).




enter image description here




Is this possible to SAVE a file thanks to Javascript, when the HTML page is accessed locally?


Note: I want to be able to silently save, not propose a Download/Save dialog box in which the user has to choose where to download, then "Are you sure to want to overwrite" etc.





Get content from websites populated with javascript


I use Simple Html Dom to scrap into websites but I have a problem. Where I inspect the page, I see a div with a specific id, but when I check the source code, that id does not appear. This means that my simplehtmldom library can't get the information inside that div.





Generate a single key from 2 strings in the both order


I would like to generate a hash from 2 different other ones. I need this to generate a key from 2 users id. I would like to be able to crypt the both id like this: crypt(<USER 1>-<USER 2>) === crypt(<USER 2>-<USER 1>).


In another word, whatever the order i crypt the both users ids, i would like the generated key to be the same every time. I do not need to uncrypt the key, just find the same key from the 2 original users id.


I am not very skilled in crypto, is there a module doing this job ?





pass parameter between two js files with express js


I wish to send variable from two different Javascript files.


router.js:



router.get('/', function(req, res){
screen_id = req.param('screen');
res.render('index',{
items:"some item"
});
});


I have another js file which called client.js, how can i have access to the items variable?


i work with ejs files.





Dealing with nanosecond timestamp strings


I have some timestamps that have resolution down to nanoseconds. I would like to be able to parse the timestamps and create Javascript Date objects (or some extension thereof) so they can be sorted/added/subtracted, etc. ... But it appears the Javascript Date object does not go beyond milliseconds.


Is there a way to extend the Date object to store the extra precision? I've looked for existing libraries that do this but haven't located any so far.


To be clear I don't need to get nanoseconds from Date.now() ... I just to be able to parse timestamp strings into objects that have the necessary precision.


JS environment is the browser (not Node.js).





JST templating Issue


So i have this issue where I create a marionette ItemView and i pass it a model. I than pass the model into the item view ECO JST template. The model JSON representation looks something like



{
"data": {
"user": {
"first_name": "first_name",
"last_name": "last_name"
},
"account": "23",
"key": "123"
}
}


The JST ECO template is something simple like :



<% console.log @ %> // returns entire object {data: object, escape: this.JST, safe: this.JST}
<% console.log @data %> // returns data object


In the JavaScript debugger. If i set a break point onto the jst template (@data.user //this.data.user) it returns the users object but when i try to inspect the user object inside the jst file i get a undefined



<% console.log @data.user %> // returns undefined


Any suggestions?


Thanks UPDATED::: ADDING Classes and Views and ECO templates



//list_controller.coffee
#user_data contains response from server.
showApiSubmit:(options) ->
apiSubmitBtn = @getSubmitButton(options)
apiSubmitBtn.on "api:submit:clicked",(model) ->
user_data = App.reqres.request("api:get:userbyid")
user = new Backbone.Model //without this the @data object doesnt show up in template at all
user.model = user_data
console.log("user_data", user_data)
data = List.Controller.getApiPopUpModal(user)
List.Controller.layout.apiResponse.show data
@layout.apiSubmit.show apiSubmitBtn

getApiPopUpModal:(model) ->
new List.PopUpModal
model: model.model

// ListView
class List.PopUpModal extends App.Views.ItemView
template: "/templates/_api_popup_modal"

//_api_popup_modal.jst.eco
<%- console.log "popup", @ %> // shows data object with user object inside
<%- console.log "popup", @data.user %> // shows undefined
<%- console.log "popup args", arguments %>
<div id ="popUpDiv">

</div>


hope this helps me find out why i cant access the user data. Thanks





Strange behavior with click event on button?


I am using jQuery File Upload plugin here for uploading files.


For each file that is added I generate a row in the table with a hidden button (that would be the single upload button for each file in the row) and another button for removing the file.


My code is below:



var addedFiles = 0;
var uploadedFiles = 0;

$('#uploadFile').fileupload({
replaceFileInput: false,
singleFileUploads: true,
autoUpload: false,
add: function (event, data) {
$.each(data.files, function (index, file) {
data.url = 'myUrl';
data.type = 'POST';
data.context = $('<tr><td><strong>Selected File : </strong>' + file.name + '</td><td><button name=singleuploadFile type="button" class="hidden">' +
'</button></td><td><button id=' + file.name + ' name=removeFile type="button" class="btn btn-default"><span class="glyphicon glyphicon-remove-circle">' +
'</span>Remove File</button></td></tr>')
.appendTo('#files');

$('button[name="singleUploadFile"]').click(function () {
if (data.files.length > 0) {
data.submit();
addedFiles += 1;
}
});

$('button[name="removeFile"]').on("click", function () {
var fileToRemoveId = this.id;
if (fileToRemoveId == data.files[0].name) {
data.files.splice(0, 1);
$(this).closest('tr').remove();
}
});
});
},
done: function () {
uploadedFiles += 1;

if (addedFiles == uploadedFiles) {
alert("All Files Uploaded");
addedFiles = 0;
uploadedFiles = 0;
}
}
});

$('#uploadAllFiles').on("click", function () {
$('button[name="singleUploadFile"]').click();
});


So you can see each individaul button for the file for Upload has a name of singleUploadFile but that button is hidden - I dont want the User to Upload Files individually. But I have a button called Upload All Files which when clicking I trigger the click event for any button with a name=singleuploadFile.


The functionality for this works and my files upload. The problem is my alert for the done function. in the click event for singleFileUpload I have a variable called addedFiles which gets incremented each time this event is hit. The done function will get called each time a file successfully uploads so I also have a variable in there called uploadedFiles - once they are equal I know that all files have uploaded so i can display this to the user. This works if I have one file and I get one created with 1 hidden singleFileUpload button. The addedFiles variable gets set to 1 and when hitting done function the uploadFiles variable is 1 and the alert fires.


However when I have 2 files - the singleFileUpload handler gets hit 3 times - the addedFiles variable therefore is 3 - done function gets hit twice as expected so uploadedFiles variable is 2 so my alert doesnt fire. For 3 files - the singleFileUpload event gets hit 6 times. For 4 files it gets hit 10 times and for 5 files it gets hit 15 times.


I cannot understand why when I have more that one row, why the click all button is triggering the singleUploadfile button the incorrect amount of times?


Update with Ekansh Rastogi answer


changed this line :



$('button[name="singleUploadFile"]').click(function () {

$(document).on('click', 'button[name="singleUploadFile"]', function () {


however my results now are:



2 files - click handler hit 4 times and added files var = 4
3 files - click handler hit 9 times and added files var = 9
4 fiels - click handler hit 16 times and added files var = 16


Update II - added the splice below - now added files wont get incremented if click handler is called for more times than there are files - slightly hacky - but seems to work for now - more testing to do....



$('button[name="singleUploadFile"]').click(function () {
if (data.files.length > 0) {
data.submit();
data.files.splice(0, 1);
addedFiles += 1;
}
});




Setting HTTP request header for all types of request in Rails


I am trying to figure out a way to send data from the browser to the server without storing it. I don't want to use a cookie.


The value is produced on the browser via javascript and I want it to be submitted with all the HTTP requests, for all methods (GET, PATCH, POST, DELETE).


I know I should probably provide some code of what I've done so far, but everything I've tried ended up to a "bump". I'm as blind as when I started looking.


I am using jQuery in my app, for all that this might be useful.


It has proven easy to do with ajax requests, but I want all types of requests.


I'm approaching the conclusion that the nature of what I want to do is apparently evil and, hence, not allowed by the relevant RFC's. My intentions are not evil at all, for the record.





Running Selenium WebDriver tests with JavaScript disabled


One of our internal applications (written in angularjs) has a special error box appearing if javascript is disabled in the browser (using noscript ), similar to the one on stackoverflow:


enter image description here I'm trying to write an automated test for it, but having difficulties.


We are using protractor, but I'm pretty sure this is not about it. Here is the protractor configuration file:



'use strict';

var helper = require('./helper.js');

exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
baseUrl: 'http://localhost:9001',

capabilities: helper.getFirefoxProfile(),

framework: 'jasmine',
allScriptsTimeout: 20000,

jasmineNodeOpts: {
showColors: true,
isVerbose: true,
includeStackTrace: true
}
};


where helper.js is:



var q = require('q');
var FirefoxProfile = require('firefox-profile');

exports.getFirefoxProfile = function() {
var deferred = q.defer();

var firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("javascript.enabled", false);
firefoxProfile.encoded(function(encodedProfile) {
var capabilities = {
'browserName': 'firefox',
'firefox_profile' : encodedProfile,
'specs': [
'*.spec.js'
]
};
deferred.resolve(capabilities);
});

return deferred.promise;
};


As you see, we are setting javascript.enabled firefox preference to false which has been proven to work if you manually open up about:config in firefox, change it to false - you would see the contents of noscript section.


But, when I run the tests, I am getting the following error:



Exception thrown org.openqa.selenium.WebDriverException: waiting for evaluate.js load failed



Here is the complete traceback.


FYI, selenium 2.44.0 and firefox 33.1.1 are used.


As far as I understand (with the help of several points raised here), disabling javascript is killing the javascript webdriver itself. Is it true? If yes, what are my options or workarounds?




Notes:




  • in case of chrome, in the past it was possible to disable javascript via --disable-javascript command-line argument, but not anymore.




  • this leads to a workaround number 0 - downgrade chrome to an old version which supported the command-line flag - this would be a not-tested plan B




  • setting javascript.enabled=false firefox preference works with python selenium bindings:



    from selenium import webdriver

    profile = webdriver.FirefoxProfile()
    profile.set_preference('javascript.enabled', False)
    driver = webdriver.Firefox(firefox_profile=profile)

    driver.get('https://my_internal_url.com')
    # no errors and I can assert the error is present



I'm open to any suggestions and can provide you with any additional information.





Toggle state of button based on select dropdown using knockout.js


I've got a small form I'm trying to add logic to, and right now I'm stuck trying to change the state of an 'add' button between enabled and disabled based on the selected value of a dropdown menu.


My DOM markup is the following:



<div>
<select data-bind="options: myOptions, optionsText: 'UserName', optionsValue: 'UserId', optionsCaption: 'Select...'"></select>
<input type="text" class="optional" />
<input class="addButton" type="submit" name="addButton" value="ADD" data-bind="enable: addButtonState" />
</div>


And my current Knockout.js code is the following:



self.addButtonState = ko.observable(false);
self.toggleAddButtonState = function () {

}


As you can see, the default value for the dropdown menu is select.... When this default is presented, I want the addButton to be in the disabled state. However, when any other option is selected, it can be enabled. The optional text field should not matter.


How can I accomplish this?





Checkbox Bubbling to div - Javascript


I have a div that is surrounding a check-box. The Div has an event handler that checks the check-box, The check-box'es default behavior is to check or uncheck itself upon being clicked, however the event is bubbling down to the div and the divs function is canceling out the check-boxes function, How can i prevent the div's function from being fired when the check-box is clicked?



<div id="CloseForMeEmailCBDIV" style="width:50px;margin-left:6px; margin-top:8px; height: 24px;">
<input id="CloseForMeEmailCB" onclick="" type="checkbox" style="margin-left:6px;margin-top:4.49px; transform: scale(2);"> Email</input>
</div>




Breaking out of a while loop and switch in one go - JavaScript


I know a similar question has been posted concerning this in C++, but I'm focusing on JS here. I'm basically in the same situation as the C++ coder in the other post



var input = prompt();
while(true) {
switch(input) {
case 'hi':
break;
case 'bye':
//I want to break out of the switch and the loop here
break;
}
/*Other code*/
}


Is there anyway to do that? Perhaps a JS version of the C++ solution. Break out of loop and switch in C++ question





Unable to parse jason returnde by the server, in file ext-all.js


I'm running some programming example's and the server send me this message: [WARN]Unable to parse json returnde by the server.


I'm using xampp stack in ubuntu 14.04, the warning points to the file ext-all.js, the page can't connect with the database. please help!!


the code is in the ext-all.js file! i didn't touch the file!





Consume WCF Webservice with angular/javascript


I'm implementing a server with WCF and trying to reach its rest services using a client developed with Angular.


Here is the service :



public interface IConnexion

{

[OperationContract]
[WebGet(UriTemplate = "Connexion/{login}/{mdp}", ResponseFormat = WebMessageFormat.Json)]
Utilisateur Connexion(string login, string mdp);

[OperationContract]
[WebInvoke(UriTemplate = "Deconnexion/{id_user}", RequestFormat = WebMessageFormat.Json)]
void Deconnexion(string id_user);


}


And my function trying to reach the service :



app.service('serverConnexionServices', function(userService, serverConfigService) {

this.Connexion = function(login, pass)
{
var uri = this.getServerUri() + "Connexion/"+login+"/"+CryptoJS.MD5(pass);

$http.get(uri)
.success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
return data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
return "";
});
};
});


my form's controller:



app.directive('loginContent', function(userService, serverConnexionServices){
return{
restrict : 'E',
templateUrl : "includes/home/login-content.html",
controllerAs: "loginController",
controller: function($scope, userService, serverConnexionServices) {

var IsSubmitEnabled = true;
this.errors = "";

this.validateLogin = function(user) { // Calling the service
this.IsSubmitEnabled = false; // To avoid more than one click while checking on the server
var retour = serverConnexionServices.TryConnection(user);
alert('retour :'+retour);
if(retour.length > 0)
{ // There is an error so we show a message to the user
this.errors = retour;
}
this.IsSubmitEnabled = true;
user = {};
};

}
}
});


But when I try to open my client the alert box appears before the breakpoint is raised in Visual Studio (I put the breakpoint on the first line of my "Connexion" function. So it means the server has not answered yet to the request but the $http.get() has already sent its answer. So the result object doesn't contain what the server is sending. According to Angular's documentation, the response will be sent asynchronously. But How can I force my request to wait the answer ?


It's my form's controller which calls "Validate Login" which calls the service "Connexion". I'd like the service to answer back so that Validate Login can show "Error while log in" or "You're logged". Now, due to the async mode my Valide Login gets an "undefined" value. How can I manage to either keep async mode but have an answer in my controller or avoid the async mode ("which may not be the better choice ?)


What's the thing I am missing ?


EDIT: I can now reach my breakpoint in the implementation of Connexion in Visual Studio but still the answer from the server is not what is expected


EDIT2 : I've added my controller which needs the refresh.





Drop down not getting displayed


Problem Question -


I have a two drop down in my view. And second drop down rely on the first one. But somehow second one does not get updated


// my firstdrop down



<select ng-controller="myController"
ng-options="customer.name for customer in customerDetailData" ng-model="customer"
ng-change="updateCost(customer)">
<option value="">Please select customer</option>
</select>


// my second drop down



<select ng-controller="myController"
ng-options="cc.name for cc in customerCostData">
<option value="">Please select cost</option>
</select>


// my controller



(function() {
var myController = function($scope,Service){
$scope.customerDetailData;
Service.cust()
.success(function(data){
console.log(data)
$scope.customerDetailData = data;
})
.error(function(status,error){

})

$scope.customerCostData;
$scope.updateCost=function(customer){
Service.cost(customer.id)
.success(function(cost){
$scope.customerCostData= cost
})
.error(function(status,data){
console.log(status);
console.log(data);
})
}
};
myController .$inject = ['$scope','Service'];
angular.module('app').controller('myController ',myController );
}());


Is anything i am missing ? the data is coming through fine in the console. Please guide me





How do I remove Edge Animate Default CSS settings using jQuery


So I want to make a Cube out of 6 squares in edge animate. I opened the HTML document and wrote this css:



.container{
-webkit-perspective: 1200px;
-moz-perspective: 1200px;
-ms-perspective: 1200px;
perspective: 1200px;
}
.cube_container{
width: 64px;
height: 64px;
position: absolute;
-webkit-transform-style: preserve-3d;
-webkit-transform-origin: 50% 50% 0;
-moz-transform: rotatex(165deg) rotateY(45deg);
-ms-transform: rotatex(165deg) rotateY(45deg);
transform: rotatex(165deg) rotateY(45deg);
}
.back_right{

-webkit-transform: translateZ(32px);
-moz-transform: translateZ(32px);
-ms-transform: translateZ(32px);
transform: translateZ(32px);
}
.right {
-webkit-transform: rotateY(90deg) translateZ(32px)rotate(180deg);
-moz-transform: rotateY(90deg) translateZ(32px)rotate(180deg);
-ms-transform: rotateY(90deg) translateZ(32px)rotate(180deg);
transform: rotateY(90deg) translateZ(32px)rotate(180deg);
} (etc...)


With that, I have a cube, fixed at a nice angle showing my textures properly.But the problem is that Edge Animate ad some css infos directly to the object (inline styling) and over write my classes. I want to know if there's a way to selectively remove css elements from edge animate, maybe from a jQuery loaded at creation complete? If You need any more information, just ask. Thank you.





Redirect with Javascript on Contact form with send.php


I'm recreating my site and I've included a contact form for users to contact me when needed. I found a javascript that redirects with a countdown timer.


contact.php:



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact Form</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="tooplate_style.css" rel="stylesheet" type="text/css" />
<script src="js/jquery.min.js"></script>
</head>
<div id="tooplate_wrapper">

<div id="tooplate_header">

<div id="site_title"><h1><a href="http://deathsrepo.pw">Technologx</a></h1></div>
<div id="twitter"><a href="https://twitter.com/Technologx" target="_blank"></a></div>

<div id="facebook"><a href="https://facebook.com/Technologx2013" target="_blank"></a></div>

<div id="tooplate_menu">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="http://deathsrepo.pw/themes.php">Themes</a></li>
<li><a href="http://blog.deathsrepo.pw">Blog</a></li>
<li><a href="http://deathsrepo.pw/store.php">Store</a></li>
<li class="last"></li>
<li><a href="http://deathsrepo.pw/contact_form.php" class="current">Contact Us</a></li>
<li class="last"></li>
</ul>
</div> <!-- end of tooplate_menu -->
<style>


body, div, h1,h2, form, fieldset, input, textarea, footer,p {
margin: 0; padding: 0; border: 0; outline: none;
}


@font-face {
font-family: 'YanoneKaffeesatzRegular';
src: url('fonts/yanonekaffeesatz-regular-webfont.eot');
src: url('fonts/yanonekaffeesatz-regular-webfont.eot?#iefix') format('embedded-opentype'),
url('fonts/yanonekaffeesatz-regular-webfont.woff') format('woff'),
url('fonts/yanonekaffeesatz-regular-webfont.ttf') format('truetype'),
url('fonts/yanonekaffeesatz-regular-webfont.svg#YanoneKaffeesatzRegular') format('svg');
font-weight: normal;
font-style: normal;
}

body { font-family: 'YanoneKaffeesatzRegular';}
p {text-shadow:0 1px 0 #fff; font-size:24px;}
#wrap {width:530px; margin:20px auto 0; height:1000px;}
h1 {margin-bottom:20px; text-align:center;font-size:48px; text-shadow:0 1px 0 #ede8d9; }


#form_wrap { overflow:hidden; height:446px; position:relative; top:0px;
-webkit-transition: all 1s ease-in-out .3s;
-moz-transition: all 1s ease-in-out .3s;
-o-transition: all 1s ease-in-out .3s;
transition: all 1s ease-in-out .3s;}

#form_wrap:before {content:"";
position:absolute;
bottom:128px;left:0px;
background:url('images/before.png');
width:530px;height: 316px;}

#form_wrap:after {content:"";position:absolute;
bottom:0px;left:0;
background:url('images/after.png');
width:530px;height: 260px; }

#form_wrap.hide:after, #form_wrap.hide:before {display:none; }
#form_wrap:hover {height:776px;top:-200px;}


form {background:#f7f2ec url('images/letter_bg.png');
position:relative;top:200px;overflow:hidden;
height:200px;width:400px;margin:0px auto;padding:20px;
border: 1px solid #fff;
border-radius: 3px;
-moz-border-radius: 3px; -webkit-border-radius: 3px;
box-shadow: 0px 0px 3px #9d9d9d, inset 0px 0px 27px #fff;
-moz-box-shadow: 0px 0px 3px #9d9d9d, inset 0px 0px 14px #fff;
-webkit-box-shadow: 0px 0px 3px #9d9d9d, inset 0px 0px 27px #fff;
-webkit-transition: all 1s ease-in-out .3s;
-moz-transition: all 1s ease-in-out .3s;
-o-transition: all 1s ease-in-out .3s;
transition: all 1s ease-in-out .3s;}


#form_wrap:hover form {height:530px;}

label {
margin: 11px 20px 0 0;
font-size: 16px; color: #b3aba1;
text-transform: uppercase;
text-shadow: 0px 1px 0px #fff;
}

input[type=text], textarea {
font: 14px normal normal uppercase helvetica, arial, serif;
color: #7c7873;background:none;
width: 380px; height: 36px; padding: 0px 10px; margin: 0 0 10px 0;
border:1px solid #f8f5f1;
-moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;
-moz-box-shadow: inset 0px 0px 1px #726959;
-webkit-box-shadow: inset 0px 0px 1px #b3a895;
box-shadow: inset 0px 0px 1px #b3a895;
}

textarea { height: 80px; padding-top:14px;}

textarea:focus, input[type=text]:focus {background:rgba(255,255,255,.35);}

#form_wrap input[type=submit] {
position:relative;font-family: 'YanoneKaffeesatzRegular';
font-size:24px; color: #7c7873;text-shadow:0 1px 0 #fff;
width:100%; text-align:center;opacity:0;
background:none;
cursor: pointer;
-moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px;
-webkit-transition: opacity .6s ease-in-out 0s;
-moz-transition: opacity .6s ease-in-out 0s;
-o-transition: opacity .6s ease-in-out 0s;
transition: opacity .6s ease-in-out 0s;
}

#form_wrap:hover input[type=submit] {z-index:1;opacity:1;
-webkit-transition: opacity .5s ease-in-out 1.3s;
-moz-transition: opacity .5s ease-in-out 1.3s;
-o-transition: opacity .5s ease-in-out 1.3s;
transition: opacity .5s ease-in-out 1.3s;}

#form_wrap:hover input:hover[type=submit] {color:#435c70;}

</style>
<body><br /><br /><br /><br />
<div id="wrap">
<h1>Contact Form</h1>
<div id='form_wrap'>
<form method="post" action="php/send.php">
<p>Hello Guest,</p>
<label for="email">Your Message : </label>
<textarea name="message" value="Your Message" id="message" ></textarea>
<label for="name">Name: </label>
<input type="text" name="name" value="" id="name" />
<label for="email">Email: </label>
<input type="text" name="email" value="" id="email" />
<input type="submit" name ="submit" value="Send" />
</form>
</div>
</div>
</body>
</html>


Here is the send.php:



<style>

body {
margin: 0;
padding: 0;
color: #9c9893;
font-family: Tahoma, Geneva, sans-serif;
font-size: 13px;
line-height: 1.7em;
background-color: #111212;
background-image: url(../images/tooplate_body.jpg);
background-repeat: repeat-x;
background-position: top center
}
</style>
<script type="text/javascript">
var count = 5;
var redirect = "http://test.deathsrepo.pw";

function countDown(){
var timer = document.getElementById("timer");
if(count > 0){
count--;
timer.innerHTML = "This page will redirect in "+count+" seconds.";
setTimeout("countDown()", 1000);
}else{
window.location.href = redirect;
}
}
</script>
<?php
if(isset($_POST['submit'])){
$to = "deathsarepo@gmail.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Help Needed";
$subject2 = "Help Needed!";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];

$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Thank you your submission was sent" . $name . ", we will contact you shortly.";
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>


The email function works but the redirection script isn't working it just stays there at the send.php. Giving the users the back button option on the browser.





AJAX call to https endopint = secure?


I am planning a Cordova mobile application (a Meteor.js app to be precise) and I need to POST/GET some sensitive data from a remote server securely.


When the request is pointed at https endpoint is it secure? My guess is that it does not work this way.


Just to say - I have read some SO questions and searched google but most of them refer to CORS problems, which I am not facing.


Thanks for any help.





Best way to create an autosave feature


What is the best way to create an autosave feature in a web application? Kind of like Google Docs.


I can already see couple of ways this could be done.


For example I could do a set interval to update the database every 30 seconds. But that would just be a waste of server resources...


What is the best way to check if an autosave is necessary? Have a duplicate of the entire database result ready and compare it every time? Is there another better way that I'm not thinking about?





Move some JSON data into unique Divs


I have a blogger.com blog and I've managed to create a script that gets the data from the blog - im not very good at js / json so I going at this a little blind ;-)


Id like the output to be in 2 DIVS that are unique with the post ID and content:


This is the script:



<html>
<head>
<title>Test</title>
</head>
<body>

<script type="text/javascript">
function posts(json) {
// Get five recent posts
for (var i = 0; i < 2; i++)
{
var posturl;
// Get rel=alternate for truly post url
for (var j=0; j < json.feed.entry[i].link.length; j++)
{
if (json.feed.entry[i].link[j].rel == 'alternate')
{
posturl = json.feed.entry[i].link[j].href;
break;
}
}
// if the Blogger-feed is set to FULL, then the content is in the content-field
// if the Blogger-feed is set to SHORT, then the content is in the summary-field
if ("content" in json.feed.entry[i]) {
var postcontent = json.feed.entry[i].content.$t;}
else
if ("summary" in json.feed.entry[i]) {
var postcontent = json.feed.entry[i].summary.$t;}
else var postcontent = "";
// strip off all html-tags
var re = /<\S[^>]*>/g;
postcontent = postcontent.replace(re, "");
// reduce postcontent to 200 characters
if (postcontent.length > 200) postcontent = postcontent.substring(0,200);
// Get posts title
document.write("Post Id = "+json.feed.entry[i].id.$t);
document.write('<br/>');
document.write("Post content = "+postcontent);
document.write('<br/><br/>');
}
}
</script>

<script src="http://ironheartuk123.blogspot.com/feeds/posts/default?alt=json-in-script&callback=posts"></script>

</body>
</html>


When I load the page into a browser I get this on screen:



Post Id = tag:blogger.com,1999:blog-5655651846573938667.post-5882120439717312684
Post content = Test post 2

Post Id = tag:blogger.com,1999:blog-5655651846573938667.post-8794205203420774123
Post content = Test post 1


And this is what I'd prefer the output to be!



<div id="5882120439717312684">Test post 2</div>

<div id="8794205203420774123">Test post 1</div>


Once I have that step done I'll be able to move the Divs into the correct position on the page. I think that's the easy bit ;-)


Any help greatly appreciated!!





Setting object property to the result of a sort without sorting


I have an array of objects, each with a property called sort_order that I need to change based on another property score but the catch is I can't actually change the order of the array which means no Array.sort().


Basically I want this:



function compare(a,b){
return b.score - a.score;
}
scores.sort(compare);


but instead of actually sorting I want to set a.sort_order and b.sort_order accordingly.





How to addUniqueObject to non-current user class using cloud code in Parse.com?


I want to add an array of current user object ID in to a user's column called "followers". Due to Parse's security reason not allowing modification to non-current user, I'm forced to use cloud code. The problem is I know nothing about JavaScript, so I need help here. Here's what I would code if no security issue mentioned above:



//add the current user ID to the user(userPassed) that the current user liked
[userPassed addUniqueObject:[PFUser currentUser].objectId forKey:@"followers"];
[userPassed saveInBackground];


To be very specific, I just want to know how to code the above in cloud code. Thanks.





How do I update a Google Map Engine Table?


I have a table in Google Maps Engine that I would like to update dynamically with JavaScript in a Google Site. I've found this help page that explains how to append features to an existing table, but I'm struggling to figure out how to modify the code so that it will update the table instead of append to it. I believe I specifically need to modify the processResponse and processErrorResponse functions. However, I'm fairly new to JavaScript/jQuery/JSON, and I'm not exactly sure how to determine what I should have instead of #insert-table-features-response. Is there someone here that could explain that to me?


Edit: To put it another way, how can I make the request shown below with JavaScript?



POST https://www.googleapis.com/mapsengine/v1/tables/{YOUR_TABLE_KEY}/features/batchPatch?key={YOUR_API_KEY}

Content-Type: application/json
Authorization: Bearer {. . .}
X-JavaScript-User-Agent: Google APIs Explorer

{
"features": [
{
"geometry": {
"type": "Point",
"coordinates": [
-82,
35
]
},
"properties": {
"Lat": 35,
"Long": -82,
"Name": "6:41:13 AM 11/27/14",
"gx_id": "123ABC456DEF7890"
}
}
]
}




hide first div before displaying next


I have four hidden divs that are shown via jquery when icons on a map are clicked. The display div shows details about each location. I want to have that display clear out each time a different location is clicked, so that only one set of details is shown at a time. Right now, whenever I click an icon, it adds to the list instead of clearing out what is currently there.


HTML:



<div id="1" class="toggle" style="display:none">test text 1</div>
<div id="2" class="toggle" style="display:none">test text 2</div>
<div id="3" class="toggle" style="display:none">test text 3</div>
<div id="4" class="toggle" style="display:none">test text 4</div>


JS:



var drawCircle = function (context, x, y, fillcolor, radius, linewidth, strokestyle, fontcolor, textalign, fonttype, filltext, div, circles) {
draw(context, x, y, fillcolor, radius, linewidth, strokestyle, fontcolor, textalign, fonttype, filltext);
var circle = new Circle(x, y, radius);
circles.push(circle);
};

drawCircle(context, 300, canvas.height / 2, "green", 40, 5, "#003300", "white", "center", "bold 32px Arial", "1", "#2", circles);
drawCircle(context, 600, canvas.height / 3, "blue", 50, 5, "#003300", "white", "center", "bold 32px Arial", "2", "#3", circles);

$('#mapCanvas').click(function (e) {
var clickedX = e.pageX - this.offsetLeft;
var clickedY = e.pageY - this.offsetTop;

for (var i = 0; i < circles.length; i++) {
if (clickedX < circles[i].right && clickedX > circles[i].left && clickedY > circles[i].top && clickedY < circles[i].bottom) {

$('#'+(i+1)).show();


}
}




compare strings to validate and display


I have a question with javascript programing about adding a word that previously I requested and verify if it is the same that I have stored in a variable and in this way show me the screen if it is the same with .


It is better to create an array and look for characters or a condition boolean?


Thanks for help!





javascript selecting a custom cursor (svg)


I'm dynamically changing a cursor to a local svg on hover with



$(element).on('mouseover', function () {
$(this).css('cursor', 'url(svgs/pointer.svg) 9 30 auto');
};


Thats working fine but I'd like to select that svg to manipulate its fill color.


Is there any way to do this so I don't have to make a bunch of different svgs with different fills?


Thanks





CanJs - Iterate through an array in mustache and create observables



...


option:{
array: new can.List([1, 2, 3, 4, 5])
}
...

{{#each option.array}}
<div>
<label for="d{{@index}}"></label>
<input id="d{{@index}}" can-value="option.array[{{@index}}]"/>
</div>
{{/each}}


Above code generates 5 text boxes with correct id. But it does not create observables.


What is the correct format that I should provide to can-value attribute to make it an observable?





jquery ui bounce effect causing elements to fall out of place


I want to create a bounce effect but when I hover the mouse over the area the elements fall out of place. How do I ensure they stay in a line?


I have three icons in a row like this



%span
=link_to image_tag("icons/github_alt.svg", class: '')
%span
=link_to image_tag("icons/last.fm.svg", class: '')
%span
=link_to image_tag("icons/soundcloud.svg", class: '')


http://jsfiddle.net/tkn02tut/


Thanks





how to hide parse config keys from client side rendering


My parse app has Parse.initialize... in some client side code for login and signup. Is there anyway to hide this when the app is rendered so that any random person can't inspect element and see it?





Use Date Library in Extendscript (Javascript)


I'm new to Indesign Scripting, but I'm working on an InDesign CC Script, where I would need to work a lot with date-functions.


I wanted to know if it's possible to import a JS Library like date.js or moment.js in Extendscript for that matter?


Cheers





RaytracerRender.js example with SSAO with black screen


I tried to implement SSAO with the Raytracer example. I wrote the following after the render was initiated:



composer = new THREE.EffectComposer( renderer );
composer.addPass( new THREE.RenderPass( scene, camera ) );

depthTarget = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat } );

var effect = new THREE.ShaderPass( THREE.SSAOShader );
effect.uniforms[ 'tDepth' ].value = depthTarget;
effect.uniforms[ 'size' ].value.set( window.innerWidth, window.innerHeight );
effect.uniforms[ 'cameraNear' ].value = camera.near;
effect.uniforms[ 'cameraFar' ].value = camera.far;
effect.renderToScreen = true;
composer.addPass( effect );


and in the calling function I wrote:



scene.overrideMaterial = depthMaterial;
renderer.render( scene, camera, depthTarget );
scene.overrideMaterial = null;
composer.render();


I am getting a black screen output.


Please help. Am I missing something? Aren't they portable in a manner where implementation of the SSAO would be free of the renderer utilized?





(beginner) HTML + JS change variables with input value


Hello Stackoverflow people,

My question is how to change a variable I assigned with JavaScript using the value of an HTML input tag.

my progress:



<script type="text/javascript">
var x = 0;
document.write(x);

function addtox() {
var addx = document.getElementById("plusx").value;
x = x + addx;
}

</script>

<input id="plusx" type="number">
<input type="button" onclick="addtox()" value="add">


The result is that it literally adds the value of id="plusx" to the 0 that's already there. So if the input would be 50, it would return 050, and not 50. If I repeat the button it returns 05050 in stead of 100.

How can I fix this?

Also: how can I update text that is already writting to the screen? x is already written to the screenbefore the change and doesn't update after it is assigned a new value.



p.s Sorry if I am a bit vague, not too familiar with coding questions like mine.





AngularJs, reducing logic in html templates


I have an html template where the conditionals in the ng-ifs and ng-shows are getting a bit too complex to belong in the UI. For example, this is to determine if payment controls should be displayed:



<div ng-show="ticket.status == 0 &&
((ticket.orgTicketId === '' && ticketControl.balance > 0 ) ||
(ticket.orgTicketId !== '' && ticketControl.balance < 0))">


I would like to simplify this to something like this:



<div ng-show="ticket.paymentsAllowed">


I would prefer to not move the logic into the controller, since I am trying to keep it as clean as possible as well.


In C#, which is where I come from, I would just add a property to the Ticket class called PaymentsAllowed and move the logic there.


I am fairly new to Javascript and AngularJs and I am looking for advice on how to accomplish something similar here, so that I can clean up the html templates and make them more legible.


The Angular app gets JSON from a WebAPI backend, which I simply assign to the $scope; this is all working well. Here is a simplified example of retrieving a ticket.


The ticketService reads the ticket view model from the backend:



function getTicket(ticketId) {
var deferred = common.$q.defer();

common.$http.get("api/tickets/" + ticketId)
.success(function (ticket) {
deferred.resolve(ticket);
}));

return deferred.promise;
}


The controller uses the ticketService to retrieve ticket and assign to $scope.ticket:



ticketService.getTicket(123).then(
function (ticket) {
$scope.ticket = ticket;
});


I like the simplicity of just retrieving view models in the form of JSON data from the WebAPI and binding it straight to the proper scope, but what is a simple, clean way to add some simple business logic to these javascript objects?





Stopping JavaScript Promises From Propogating


Imagine I have a promise chain like the one below. If func2 is called, I would like to avoid func3 or func4 from being called altogether.



AsyncFunction()
.then(func1, func2)
.then(func3, func4)


At the moment, If I throw an error in func2, func4 would be called. If I return a value in func2, func3 seems to be called.


I am using Angular $q.





Dynamically adding elements to a div aren't included in $.each call


I have a div on my page where the contents are messages. The messages are auto loaded when the page loads via javascript. Each message has the basic structure:



<div class="conversationMessage"></div>


Then there is a button, which when clicked will loop through all messages and hide/show the messages if they have a specific id:



$("tr[id|='mstrTopic']").click(function(){
var clicks = $(this).data('clicks');

if(clicks)
{
var splitText = $(this).attr('id').split('-');
$('.conversationMessage').each(function(index, value){
if($(value).find('.topicFlipFront').attr('rel') == splitText[1])
$(value).show();
});
}
else
{
var splitText = $(this).attr('id').split('-');
$('.conversationMessage').each(function(index, value){
if($(value).find('.topicFlipFront').attr('rel') == splitText[1])
$(value).hide();
});
}
$(this).data("clicks", !clicks);
});


The issue I'm having is that after all the javascript has loaded and the messages are auto loaded, if any additional messages are added, they won't be hidden or shown when the button is clicked.


The code below sits in the document ready function. I've also tried putting it into the code which adds new messages, however when 2 more more messages are added, it stops working. Can anyone point out where I'm going wrong and how I can make this work?





Resize image to fill div


I have the following function to resize an image to fill its container div without skewing the image. It uses css to fill by height and if the image is not wide enough to fill the div then the function uses width to fill the div and sets height to auto. The problem is the code only works with window.load, so if the user is paying attention they can see the image load, then after a second it changes. So how would I change the function to work with document.ready?



function imageResize() {
$(".square").each(function(){
if($("img",this).width() < $(this).width()){
$("img",this).css("height", "auto");
$("img",this).css("width", "100%");
}
});
}




JavaScript: Re-order an array


I read a few answers on SO about the problems when dealing with splice (including Move an array element from one array position to another) but I was unable to solve my problem.


I am trying to reorder an array in a particular pattern. Let's assume the pattern is that all the negative numbers should be to the left of the array and all the postive numbers should be to the right of the array. The negative and positive numbers should be separated by zeros if any. It is important that the order be maintained



Sample Input = [3,0,2,-1,0,-3]
Desired Output = [-1,-3,0,0,3,2]


This is the code I wrote



function reorderArray(inputArray) {
origLength = inputArray.length
var indexZero = -1;
for (var i = 0; i < origLength; i++) {
if (inputArray[i] > 0) {
inputArray.push(inputArray[i]);
inputArray.splice(i, 1);
} else if (indexZero == -1 && inputArray[i] == 0) {
indexZero = i;
} else if (indexZero != -1 && inputArray[i] < 0) {
inputArray.splice(indexZero, 0, inputArray.splice(i, 1))
indexZero++;
}
}
alert(inputArray);
}


I run into a problem in the first step itself where I attempt to move all positive numbers at the back of the array because of the re-indexing. I can't start from the last index because that would mean losing the order and I can't use the i-- since it would run infinitely.


Any help with how I could make my code work would be appreciated. Additionally, if there is an alternative that is more efficient than splice, that would be welcome too.


Thanks.





Javascript game code not console logging


Hey im new at javascript and im doing a rock, paper, scissors, lizard, spock game for class. Instead of using switch statements I decided to use continuous if, else if statements to make sure I account for every circumstance that I may encounter. My program is finished, the computer picks a random choice, users pick their choice, however the computer will not console log the statements if a circumstance occurs. I've tried for hours and cannot come up with a solution. My program is 350 lines long but here are the first few. The other lines are exactly the same but just have different choices for choice1 and choice2. Please help. Thank You in advance



var userChoice1 = prompt("Choose rock, paper, scissors, lizard, or spok")
var userChoice2 = prompt("Choose rock, paper, scissors, lizard or spok")
var computerChoice = Math.random();
if (computerChoice < 0.2) {
computerChoice = "rock";
} else if (computerChoice <= 0.4) {
computerChoice = "paper";
} else if (computerChoice <= 0.6) {
computerChoice = "scissors";
} else if (computerChoice <= 0.8) {
computerChoice = "lizard";
} else if (computerChoice <= 1.0) {
computerChoice = "spock";
}

console.log("Computer chose " + computerChoice);
console.log("Player 1 chose " + userChoice1)
console.log("Player 2 chose " + userChoice2)

var compare = function(choice1, choice2, choice3){
if (choice1 === choice2 === choice3) {
console.log("It's a tie!");
}


else if (choice1 === "rock", choice2 === "rock") {
if (choice3 === "scissors" ) {
console.log("Rock crushes both scissors.");
} else if (choice3 === "paper") {
console.log("Paper covers both rocks. ");
} else if (choice3 === "lizard") {
console.log("Rocks crush the lizard. ");
} else if (choice3 === "spock") {
console.log("Spock vaporizes both rocks. ");
}
}




Is var { Route, Redirect, RouteHandler, Link } = Router; valid in Javascript?


What does this mean in Javascript ? I found this in react-router examples



var { Route, Redirect, RouteHandler, Link } = Router;


I get the following error when it is run through browserify.



"Uncaught SyntaxError: Unexpected token {"


https://github.com/rackt/react-router/blob/master/examples/dynamic-segments/app.js


Esprima also gives the same error: http://esprima.org/demo/validate.html





How to show notification bar if there is a new post in Wordpress?


Can someone help me with the following. I want an alert bar at the top of my Wordpress website, when there is a new post published on my blog. So the users are known that there is a new post available.


So I downloaded a Wordpress plugin called: WPFront Notification Bar Only the problem is that I only can set this bar on or off. But not show this bar automatically when there is a new post and after a day it will reset the value to off and will only be switched back to on if there is a hole new post.


So I thought if I make in my header.php a notification bar like the plugin, style it to my website and add some javascript to it. Only the problem is, I don’t know how to do this and also can’t find something on the internet so the reason for this question is written above.


Hopefully someone can help me out!





samedi 29 novembre 2014

jquery ajax post href value without refreshing the page


Hello I want to post link value e.g. href="?id=1" my link


but without refreshing the page current it refreshes the page but i dont want reloading of the page, here is my code please help me



function loadTabContent(tabUrl){
$("#preloader").show();
jQuery.ajax({
type: post,
url: tabUrl,
data: "id="+country_id,
cache: false,
success: function(message) {
jQuery("#tabcontent").empty().append(message);
$("#preloader").hide();
}
});
}

jQuery(document).ready(function(){

$("#preloader").hide();
jQuery("[id^=tab]").click(function(){

// get tab id and tab url
tabId = $(this).attr("id");
tabUrl = jQuery("#"+tabId).attr("href");

jQuery("[id^=tab]").removeClass("current");
jQuery("#"+tabId).addClass("current");

// load tab content
loadTabContent(tabUrl);
return false;
});
});




Copying newlines in JavaScript alert to clipboard


Is this simply a browser issue or am I formatting content wrong?


I'm calling alert("This\nis\na\ntest"); and then pressing Ctrl + C to copy the contents of the alert message to my clipboard. This is working, except that the text copied to my clipboard doesn't contain the newlines. I've tried \r\n as well and although it prints the newlines in my alert box, they don't get copied to the clipboard in Chrome on Windows 8.


Is there a newline character I'm not using or is this a limitation I can't fix?


See this JSfiddle: http://jsfiddle.net/oscsy07b/1/


Thanks.





2 Images display at the same time


I am using JSSOR SLIDER in my page and it works but not properly.


When the first image is displayed, some portion of the second image is also shown. How to remove that ?



<script type="text/javascript" src="js/jssor.js"></script>
<script type="text/javascript" src="js/jssor.slider.js"></script>

<script>
jQuery(document).ready(function ($) {
var options = { $AutoPlay: true };
var jssor_slider1 = new $JssorSlider$('slider1_container', options);
});
</script>


<div id="slider1_container" style="position: relative; top: 0px; left: 0px; height: 400px;">
<div u="slides" style="cursor: move; position: absolute; overflow: hidden; left: 0px; top: 0px; height: 300px;">
<div><img u="image" src="images/home1.jpg" /></div>
<div><img u="image" src="images/home2.jpg" /></div>
<div><img u="image" src="images/home3.jpg" /></div>
<div><img u="image" src="images/home4.jpg" /></div>
</div>
</div>


Can anyone help me, that 2 images are not shown at the same time.





ASP.NET Custom Control, Two Grids.. Need some advice


I need some advice designing a custom control which uses two grids and an Add and Remove button in between.


The Add button takes the selected item from left and add it to the right and then it removes it from the left.


The Remove button does the vice versa.


To have a fluid experience, I understand that Javascript will probably have to be involved.


Currently I'm creating a control inheriting CompositeControl with two grids and two sources. I could use a UpdatePanel so I don't have to do do a full post back on Add/Remove.


Any suggestions on the best way to approach this?





Convert Blob to binary string synchronously


I'm trying to put image in clipboard when user copies canvas selection:


canvas selection


So I thought the right way would be to convert canvas tu dataURL, dataURL to blob and blob to binary string.


Theoretically it should be possible to skip the blob, but I don't know why.


So this is what I did:



function copy(event) {
console.log("copy");
console.log(event);

//Get DataTransfer object
var items = (event.clipboardData || event.originalEvent.clipboardData);
//Canvas to blob
var blob = Blob.fromDataURL(_this.editor.selection.getSelectedImage().toDataURL("image/png"));
//File reader to convert blob to binary string
var reader = new FileReader();
//File reader is for some reason asynchronous
reader.onloadend = function () {
items.setData(reader.result, "image/png");
}
//This starts the conversion
reader.readAsBinaryString(blob);

//Prevent default copy operation
event.preventDefault();
event.cancelBubble = true;
return false;
}
div.addEventListener('copy', copy);


But when the DataTransfer object is used out of the paste event thread the setData has no longer any chance to take effect.


How can I do the conversion in the same function thread?





for loop execute slow for large data


I have a for loop that take too long for execute for large amount of data:



for (var itm = 0; itm < itmCount; itm++) {

var curObj = $('[aria-describedby=' + gridName + '_' + columnNames[itm].name + ']');

var thisCell = $('#' + gridName + '_' + columnNames[itm].name + ' div');
$('#widthTest').html(thisCell.text()).css({
'font-family': thisCell.css('font-family'),
'font-size': thisCell.css('font-size'),
'font-weight': thisCell.css('font-weight')
});
var maxWidth = Width = $('#widthTest').elementRealWidth() + 17;

var itm2Count = curObj.length;
// Loop through Rows
for (var itm2 = 0; itm2 < itm2Count; itm2++) {

var thisCell = $(curObj[itm2]);

$('#widthTest').html(thisCell.html()).css({
'font-family': thisCell.css('font-family'),
'font-size': thisCell.css('font-size'),
'font-weight': thisCell.css('font-weight')
});

thisWidth = $('#widthTest').elementRealWidth();
if (thisWidth > maxWidth) {maxWidth = thisWidth+10;}
}

$('#' + gridName + ' .jqgfirstrow td:eq(' + itm + '), #' + gridName + '_' + columnNames[itm].name).width(maxWidth).css('min-width', maxWidth+17);
$('#' + gridName + ' .jqgfirstrow td:eq(' + 0 + '), #' + gridName + '_' + columnNames[0].name).width('30').css('min-width', '30px');


I get this issue from firefox: A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue.


and the chrome kills the page. Any idea?





Can't access methods on object's prototype


I can create a Cat object and set a method on it's prototype to print out the cat's name.





var log = function(message) {
var results = $('#result');
results.append('<p>' + message + '</p>');
};

function Cat(name) {
this.name = name;
}

Cat.prototype.speak = function() {
log('My name is ' + this.name);
};

var fluffy = new Cat('Fluffy');
var tiddles = new Cat('Tiddes');

log(fluffy.name);
fluffy.speak();
log(tiddles.name);
tiddles.speak();



<script src="http://ift.tt/1oMJErh"></script>
<div id="result"></div>



However, when I try to set the cat's prototype to an animal, I can't access the speak method:



function Animal(name, sound) {
this.name = name;
this.sound = sound;

this.speak = function() {
log(sound + '! My name is ' + name);
};
}

function Cat(name) {
this.prototype = new Animal(name, 'Meow');
}

var fluffy = new Cat('Fluffy');

fluffy.speak(); // TypeError: undefined is not a function


Why does fluffy not get the speak() method of its prototype?





jQuery redirect not working with Rails each-loop


I have a Rails site where creating a new post responds to JavaScript.


I'm also using the private_pub gem and trigger a push message after creating the post.


The user should be redirected to the post after it has been created.


This is the content of create.js.erb:



<%= @users.each do |user| %>
<% publish_to "/user/#{user.id}" do %>
$("#messages").prepend("<%= j render(@message) %>");
<% end %>
<% end %>

var url = "/posts/<%= j @post.id %>";
$(location).attr('href',url);


The push message is working fine, but the user is not redirected.


If I remove the each-loop, the redirection works. Any other code is not influenced by the loop at all, also the position in the file doesn't change anything. I've tried many different approaches but haven't found any solution.





Setting global variables but not getting expected result [duplicate]



This question already has an answer here:




I am having a problem setting some global variables to use outside of the script that I am writing. I believe that I am setting them correctly but they don't seem to be cooperating. My console output is always an empty string, where as they are supposed to be defined inside the primary calling function of the demo web page. All of the other data seems to be working fine, if I print it out without setting it to a variable then it works fine. However I need the variables so that I can call them outside of this script. Any ideas?



var latitude = "", longitude = "";


$(document).ready(function() {
$.ajax({
dataType: "json",
url:"http://api.geonames.org/searchJSON?q=Atlanta&maxRows=10&username=Demo"
}).then(function(data){
console.log(data);
latitude = data.geonames[0].lat; <---Variables are supposed to be set here
longitude = data.geonames[0].lng; <----Variables are supposed to be set here
$('.map-Latitude').append(data.geonames[0].lat); <----Works well
$('.map-Longitude').append(data.geonames[0].lng); <----Works Well
});
});


console.log("Latitude is: " + latitude); <---- prints out an empty string
console.log("Longitude is: " + longitude); <---- prints out an empty string


I cant seem to get this to work, I feel like I am setting the variables properly but they don't seem to be working well. Thanks!





Pull an HTML file into a TinyTest


TinyTest seems to be concerned only with unit testing; however, may Meteor packages have UI elements, and it would be helpful to pull in a pre-crafted HTML file that exercises a widget. For instance, we might want to transform a <table> into a grid with DataTables.net, then test if the instantiation was correct.


How can external HTML files be used in a TinyTest?


package.js:



Package.onTest(function (api) {
api.use(packageName, where);
api.use(['tinytest', 'http'], where);

// TODO we should just bring in src/test.html - but how to do that with TinyTest?
api.addFiles('src/test.html', where); // this won't magically display the HTML anywhere
api.addFiles('meteor/test.js', where);
});


test.js:



Tinytest.addAsync('Visual check', function (test, done) {
var iconsDropZone = document.createElement('div');
document.body.appendChild(iconsDropZone);


// TODO ideally we'd get src/test.html straight from this repo, but no idea how to do this from TinyTest
HTTP.get('https://rawgit.com/FortAwesome/Font-Awesome/master/src/test.html', function callback(error, result) {
if (error) {
test.fail('Error getting the icons. Do we have an Internet connection to rawgit.com?');
} else {
iconsDropZone.innerHTML = result.content;
test.ok({message: 'Test passed if the icons look OK.'});
}

done();
});

});




Cross Origin XMLHttpRequest iFrame "Mini Browser"


Is it possible to get around the security and mimick either a full-browser or mobile browser within a webpage?


I had an idea to set the HTML manually, using an AJAX/XMLHttpRequest ("Get" request)



document.querySelector('#myiframe').contentWindow.document.write("<html><body>Hello
world</body></html>");


(from How to set HTML content into an iframe in IE8, IE9)


Can anyone verify this is possible? I'm guessing you would lose relevant site date (cookies, cache, etc)





How do I bold one line in a Google Docs Script?


I'm writing a script to parse a Google Sheet and format the cells nicely on a Doc. I'd like the cell data from column 1 to always be bold and the cell data from column 6 to always be Italic. The problem is, after appending a paragraph to the document body, the attribute changes are applied to the entire document. Is there a way to bold/italicize the cell data before appending it to the doc body?



function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();

var doc = DocumentApp.create("Smogon Formatted");
var docBody = doc.getBody();

for (var i = 2; i <= numRows; i++) {

for (var j = 1; j <= numCols; j++){

var cellData = rows.getCell(i, j).getValue()

// Format data based on column
if (j == 1) {
docBody.appendParagraph(cellData).editAsText().setBold(true);
} else if (j == 2 || j == 3) {
var imgFormula = rows.getCell(i, j).getFormula();
var imgUrl = getImageUrl(imgFormula);
docBody.appendParagraph("[img]" + imgUrl + "[/img]");
} else if (j == 6) {
docBody.appendParagraph(cellData).editAsText().setItalic(true);
} else {
docBody.appendParagraph(cellData);
}
}
}
};


EDIT: Try #2, using the setAttributes method



function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();

var doc = DocumentApp.create("Smogon Formatted");
var docBody = doc.getBody();

for (var i = 2; i <= numRows; i++) {

for (var j = 1; j <= numCols; j++){

var cellData = rows.getCell(i, j).getValue()

// Format data based on column
if (j == 1) {
docBody.appendParagraph(cellData).setAttributes(style1);
} else if (j == 2 || j == 3) {
var imgFormula = rows.getCell(i, j).getFormula();
var imgUrl = getImageUrl(imgFormula);
docBody.appendParagraph("[img]" + imgUrl + "[/img]");
} else if (j == 6) {
docBody.appendParagraph(cellData).setAttributes(style2);
} else {
docBody.appendParagraph(cellData);
}
}
}
};

// Style definitions as global variables
var style1= {};
style1[DocumentApp.Attribute.BOLD] = true;
var style2= {};
style2[DocumentApp.Attribute.ITALIC] = true;