mercredi 31 décembre 2014

remove third-level navigation wordpress


We're using a theme that has responsive navigation... but it's pretty bad on the third-level. I'd like to remove that level completely on devices less that 768px wide.


Does anyone have an idea of how to do this? All of the navigation elements seem to be converting to <option>... is there a way to tell it to only do this to top- and second-level navigation?


http://ift.tt/1EJiKul


Thank ya!





How to convert a Buffer object to a file in Node.js?


I'm developing a web application using (MySQL)EAN stack. I saved png/jpg/pdf as BLOB in MySQL. Now, I can retrieve them as Buffer objects in Node.js by using Sequelize.js:



exports.loadUploadedFiles = function(req, res) {
db.File.findAll().success(function(files) {
//res.send(files[0].dataValues.data.toString('ascii')); // I have tried to convert a Buffer to ascii and sent it to Angular.js, however, I still don't know how to transform them to a file link.
res.send(files); // How can I return the Buffer objects to Angular.js
}).error(function(err) {
console.log(err);
res.sendStatus(500);
});
};


I have tried two approaches:




  • Return the Buffer objects to Angular.js, then, find a way to generate downloadable links from them.




  • Convert the Buffer objects to ascii by using bufferObject.toString('ascii'), then, find a way to transform these ascii to downloadable links




I have been trying for a day and still can't figure it out in both approaches :( , any suggestion would be highly appreciated!





Problems with ajax and session variable in Web2Py


I'm developing an app in Web2Py that consists in a little e-commerce. Have a controller and page that the link is localhost:8000/topranchos/produto, with products, were topranchos is the app.


In the page produto there are a list of products like this:


The image is in this link


When the button "Adicionar ao carrinho" is clicked, the javascript function is executed:



<script>
function adicionarCarrinho(prod, qtde) {
quantidade = document.querySelector(qtde).value
console.log(quantidade)
if(quantidade > 0) {
$.get("{{=URL(f="adicionarCarrinho")}}", {produto: prod, qtde: quantidade} )
.done(function( data ) {
console.log (data)
var atual =document.querySelector(".badge-carrinho").innerHTML;
document.querySelector(".badge-carrinho").innerHTML =
parseInt(quantidade) + parseInt(atual);
alert("Adicionado ao carrinho com sucesso");
});
}
else alert("Selecione a quantidade de itens deste produto que você deseja");
}
</script>


It's make a requisition to the action default/adicionarCarrinho:



def adicionarCarrinho():
if request.vars:
session.carrinho.append(
#{'produto':db(db.produto.id == request.vars['produto']).select(),
{'produto':int(request.vars['produto']),
'quantidade':int(request.vars['qtde'])}
)
print "----------"
print session.carrinho
return str("OK")


Where session.carrinho have a list that was declared on db.py model:



#carrinho
session.carrinho = []


On the terminal, the command print session.carrinho print the item received by the ajax request, but when I add other itens the list is empty. When I click on the page of carrinho, that shows the session.carrinho's informations, the var is empty.


How can I repair this? I tried use cookies of course Web2Py book, but I dummie on Web2Py and not has success yet :/


thank you!





Loading handsontable with local data fails


I am trying to use http://ift.tt/13Kis5t to load some data which I have included into a handsontable view. Although the JS is valid:



$(document).ready(function () {

function getCarData() {
return [
["Nissan", 2009, "black", "black"], ["Nissan", 2006, "blue", "blue"], ["Chrysler", 2004, "yellow", "black"], ["Volvo", 2012, "white", "gray"]];
}

var data = [
["", "Kia", "Nissan", "Toyota", "Honda"],
["2008", 10, 11, 12, 13],
["2009", 20, 11, 14, 13],
["2010", 30, 15, 12, 13]
];




$("#example1").handsontable({
data: data,
minRows: 5,
minCols: 6,
minSpareRows: 1,
currentRowClassName: 'currentRow',
currentColClassName: 'currentCol',
autoWrapRow: true,
rowHeaders: true,
colHeaders: true
});


$("#example1").handsontable('selectCell', 3, 3);





});


The load is not occurring. Why and how can I fix this?





Change a image when list box selected item is changed


I have a list box with id of 'availmap' containing filename of images the path is maps/image.jpg


I also have a image control with id of 'map' that I would like to change to the selected image using the onclick event of the list box


this is the js I have tried and can not figure out why it won't work



<script type="text/javascript">
function ChgImg() {
var list = document.getElementById('availmap');
var indx = list.selectedIndex;
var img = list[indx].value;
var id = document.getElementById('map');
id.src="maps/" + img;


}


This is the image tag and the listbox code



<div id='avail' style='position:fixed;left:500px;top:0;z-index:0;text-align:center;bgcolor='#00b0e6';>
<span style='position:fixed;left:540px;top:30px;width:250px;font-family:Arial;font-size:15px;background-color:#00b0e6;border: 1px #000000 solid;'>Availible Maps</span> </div>
<form action='jobs.php' target='joblist' style='position:fixed;left:500px;top:101px;'></td>

<select id='availmap' name='availmap' size='10' style='width: 250px;position:fixed;left:540px;top:51px;' onchange='ChgImg()'>
EOY;
while($row = mysqli_fetch_array($mapresult))
{
echo "<option value=\"".$row['ID']."\">".$row['AssocMap']."</option>\n ";
}

echo "</select>";

echo "</form>";

echo "<img id='map' src='' alt='' style='position:absolute;left:800px;top:30px;width:260px;height:185px;border: 1px #000000 solid;'>";


I'm sure it is something relatively simple I am missing here





Radio Buttons Require two Clicks to Show as Selected in Browser


This quirky behavior is happening inside a wizard page (single page style app). That being where the page is loaded once but one <div> is loaded multiple times with different partial pages. In order to trigger the two clicks needed behavior, the partial page containing the radio buttons must be loaded once (everything works) then user advances to the next page in the wizard and then goes back to the first page with the radio buttons (quirky behavior). Navigation is controlled by code outside the <div> and not the browser buttons.


The radio buttons are contained inside a kendoWindow control and inside that window there is one radio button per row in a kendoGrid control. The data for the grid is loaded from a data source in the mvvm javascript code. Here is the template for the grid rows and the grid.



<script type="text/x-kendo-template" id="grid-radio-template">
<input type="radio" name="service_location_radio" value="#=MasterId#" data-bind="checked: service_location, events: { change: service_location_click }"/>
</script>

<div id="ServiceLocationSearchGrid"
class="specify-service-location-section specify-service-location-field"
data-role="grid"
data-scrollable="true"
data-resizeable="true"
data-sortable="true"
data-bind="source: service_location_results, visible: ShowServiceLocationsSection, events: { dataBound: ServiceLocationSearchGridDataBound }"
data-auto-bind ="false"
data-pageable="true"
data-columns="[{ template: kendo.template($('#grid-radio-template').html()), width: 40 },
{ field: 'Designator', title: 'Designator(s)'}
]"></div>


As I mentioned, everything works fine on the first pass on the wizard page, however, if the user leaves and returns the radio buttons require two clicks to visually see the radio button is selected. I have debugged into both the change and click events. Everything inside the mvvm is working correctly, on the first click of the radio button, the events fire and the service_location property is updated correctly, but the radio buttons (all of them) are not selected. When I click a second time, all the events fire again, the exact same data shows in the mvvm and finally the ui shows the radio button is selected.


I have tried unbinding the mvvm, destroying the kendoWindow widget and deleting the variable (it is a property on another variable) when the user leaves the page, but to no avail. Everything is recreated when the user returns to this page.



kendo.unbind('#specify-service-location');

$('#specify-service-location').data('kendoWindow').destroy();

delete ScenarioManager.Location.ServiceLocationSearchModel;


There should not be anything left hanging around when the kendo window is displayed a second time, but I still think this may be a possibility given that this is a single page style app. Is there anything that I am missing as far as what needs to be removed or how things are removed from memory that could clear this up? Or have I missed something entirely?





Web Audio API's AnalyserNode alternative for Node.js


Audio analysis in web browser can be easily performed by AnalyserNode of Web Audio API.


Is there something similar for Node.js?





Playing audio clips and lag in javascript


I'm having an issue with lag in javascript. I have many clips of audio a user can click on. I have a global "audioPlayer" that I start/pause and redefine everytime I play/stop something. But suppose I click on and off of the posts many times. Even though the posts stop and start as as they should, there's a HUGE lag before the last one plays. Such a large lag, too, that I believe instead of playing just the current audio player audio it's loading all previous audio from the posts I started to load and play and then stopped, even though it will only play the post most recently clicked. How should I fix this?



function didFinishPlayingAudio() {
IS_PLAYING_SHOUT=false;
alert("finished audio playing!")
}

var animationDiv;
var CURRENTLY_PLAYING_SHOUT;
var IS_PLAYING_SHOUT;
var audioPlayer;
function playShout(sender) {
console.log(sender.id)
var uniqueIdentifier;
if (sender.nodeName.toLowerCase() === "span") {


uniqueIdentifier=sender.parentNode.id
} else if (sender.nodeName.toLowerCase() === "img") {

uniqueIdentifier=sender.id

}
var shout;
for (i=0;i<shoutsArray.length;i++) {
if (shoutsArray[i].id==uniqueIdentifier) {
shout=shoutsArray[i];
}
}
CURRENTLY_PLAYING_SHOUT=shout;
var shoutAudioUrl=shout.get("audioData").url()

if (!IS_PLAYING_SHOUT) {
playAudioAtUrl(shoutAudioUrl)

} else {
if (shoutAudioUrl==audioPlayer.src) {
<!-- clicked on shout thats already playing-->
audioPlayer.pause();
audioPlayer=null;
IS_PLAYING_SHOUT=false;
console.log("stopped audio player")
} else {
playAudioAtUrl(shoutAudioUrl)
}
}
}

function playAudioAtUrl(url) {
console.log(url)
if (IS_PLAYING_SHOUT) {
audioPlayer.pause();
audioPlayer=null;
}
console.log("playin dat audio")
audioPlayer = new Audio(url);
audioPlayer.addEventListener("ended", didFinishPlayingAudio);
audioPlayer.id="shoutAudioPlayer"
audioPlayer.play();
IS_PLAYING_SHOUT=true;
}




Flexible Custom Layout with CSS (possibly JS if needed)


As per the attached image. I am trying to make a <ul> that contains multiple items. However, I want the first five items to always fill the viewport height and if there are more than five items I need the rest to have the same height as the first five <li>'s.


As per li number 4 in the image, there maybe be a nested <ul> that can fill the width having multiple <li>'s.


The text inside all <li>s needs to be vertically centered and supports multi-line while retaining the same height as the other elements.


NOTE: Any other lis below the fold need to have the same height as the initial first five. (Even if there are less than five elements at first, they shouldn't fill the full height. Only when there are five they complete the full page height.


Any help is greatly appreciated! My previous question was not full and I missed some explanations: Vertically Stretch List Items I am using the CSS only solution (for now) which doesn't work as needed.


Thanks.enter image description here


CODE Used:



ul.navigation {
list-style-type: none;
margin: 0;
padding: 0;
display: table;
width: 100%;
height: 100%;
}
ul.navigation li {
display: table-row;
}
ul.navigation li a {
font-size:1.8em;
display: table-cell;
vertical-align: middle;
padding: 1em 1.1em;
text-transform: uppercase;
color: white;
text-decoration: none;
}




Function that can return a value and also act as an object


This question seems hard to form so I will just provide an example of what I am trying to accomplish::



function test(word) {
return word
}

function replaceWord(word) {
return word
}
test('Hello').replaceWord('World')


So I want to be able to return "Hello" and if I want to, chain the replaceWord function.


Comparable to how jquery handles things like



$('#element').something('doit').somethingElse();


I feel like I am on the right track with



var test = function (word) {
return word;
}
test.prototype = {
replaceWord: function (word) {
return word;
}
}


But since I am returning the string, the chain will not work. What is the proper way I am supposed to doing this to be be able to have a function that can return a value [test('Hello')] and also can act as an object to modify data for value/s returned by the function [test('Hello').replaceWord('World')]?





JavaScript runtime error: Unable to get property 'top' of undefined or null reference


When using IE10 I am getting the error JavaScript runtime error: Unable to get property 'top' of undefined or null reference when trying to click a hyperlink to a webpage within the same project, the JavaScript should scroll to the corresponding position on the page.


If I use any other browser, other than IE it works from page to page. If however I use the same references within the same page it will scroll up and down in all browsers, but not in IE when leaving the page.


Link



<li><a href="index.html#home_section">Home</a></li>


I am using jquery.nav.js version 3.0.0 and the page is breaking at var offset = $(target).offset().top;.


Any help would be much appreciated :-)





Logic for implementing output of a function to another function


I have 2 input check boxes and a select list. what i want to do is, whenever a checkbox is selected, a certain amount is added into the element with the "amount" as id. The basic product price is 6000 and whenever a checkbox is selected, a certain amount is added to that basic product price. This goes the same for select box which has 10 input values. Each value is multiplied with 600 and the result is then added in the element with "amount" as id.


Check out the JSFiddle for the complete understanding.



http://ift.tt/1EJMDeg


This is what i tried for the select box.



function ep(t)
{
// addedprice = 0;
var addedprice = t.value * 600;
total = total + addedprice;
// total = 6000 - total;
document.getElementById('total').innerHTML = " (+) "+ addedprice;
loginer = document.getElementById('login').checked;
profer = document.getElementById('prof').checked;
if(t.value > 0)
{
// total = total + addedprice;
if(wpress)
{
wp(addedprice);
}
if(blogger)
{
blog(addedprice);
}
if(loginer)
{
login(addedprice);
}
if(profer)
{
prof(addedprice);
}
}

document.getElementById('amount').value =6000 + total;
total = 6000 + total;
document.getElementById('amount').value = total;
}


I need to implement this in Javascript.





Switch from Bootstrap to Foundation JS errors with Poltergeist


Recently we made the switch from Bootstrap to Foundation and naturally a bunch of our feature tests are breaking with Capybara (with a Poltergeist driver). When I run my "suite" (only using one test example here), I get the following error:



1) AccountManagement adding a new account and skipping payments integration
Failure/Error: sign_in_with www_sign_in_url, account.owner.email, 'valid_password'
Capybara::Poltergeist::JavascriptError:
One or more errors were raised in the Javascript code on the page. If you don't care about these errors, you can ignore them by setting js_errors: false in your Poltergeist configuration (see documentation for details).

SyntaxError: Parse error
SyntaxError: Parse error
# /Users/.rvm/gems/ruby-2.1.2/gems/poltergeist-1.5.1/lib/capybara/poltergeist/browser.rb:275:in `command'
# /Users/.rvm/gems/ruby-2.1.2/gems/poltergeist-1.5.1/lib/capybara/poltergeist/browser.rb:29:in `visit'
# /Users/.rvm/gems/ruby-2.1.2/gems/poltergeist-1.5.1/lib/capybara/poltergeist/driver.rb:89:in `visit'
# /Users/.rvm/gems/ruby-2.1.2/gems/capybara-2.4.4/lib/capybara/session.rb:227:in `visit'
# /Users/.rvm/gems/ruby-2.1.2/gems/capybara-2.4.4/lib/capybara/dsl.rb:51:in `block (2 levels) in <module:DSL>'
# ./spec/support/features/session_helpers.rb:12:in `sign_in_with'
# ./spec/features/account_management_spec.rb:19:in `block (2 levels) in <top (required)>'
# ./spec/rails_helper.rb:115:in `block (3 levels) in <top (required)>'
# ./spec/rails_helper.rb:112:in `times'
# ./spec/rails_helper.rb:112:in `block (2 levels) in <top (required)>'


Unfortunately, when I checkout the "www_sign_in_url" I don't see any JS errors in the chrome console.


This is what the suite looks like:



require 'rails_helper'

feature "AccountManagement", :type => :feature do

let!(:port_number) { 3001 }
let!(:account) { create(:account, owner: create(:owner, password: 'valid_password', confirmed_at: Time.now, tour: true)) }
let!(:sign_in_url) { "http://#{account.subdomain}.lvh.me:#{port_number}/admin/sign_in" }
let!(:www_sign_in_url) { "http://ift.tt/1zR5VLw" }
let!(:store_url) { "http://#{account.subdomain}.lvh.me:#{port_number}/" }
let!(:sign_up_with_stripe) { "http://#{account.subdomain}.lvh.me:#{port_number}/admin/payment_integration" }

before(:each) do
Capybara.server_port = port_number
Capybara.app_host = root_url
Capybara.default_wait_time = 15
end

scenario 'adding a new account and skipping payments integration', :js => true do
sign_in_with www_sign_in_url, account.owner.email, 'valid_password'
expect(page).to have_content('Manage stores')

click_on 'Add store'
expect(page).to have_content('Basic Store Info')

fill_in "account[business_attributes][name]", with: 'newstore'
fill_in "account[subdomain]", with: 'newstore'

click_on 'Skip payment setup'

expect(page).to have_content('Welcome')
end


This is what the sign_in_with method looks like:



def sign_in_with(sign_in_url, email, password, user_type = 'user')
visit sign_in_url
fill_in "#{user_type}[email]", with: email
fill_in "#{user_type}[password]", with: password
click_button 'SIGN IN'
end


Where else can I check for a JS error if not the chrome console?





Dynamically adding dropdown and Textbox by user


can anyone help me on the below I developed a code below for dynamically adding text boxes but i need to do the same for drop down boxes and the value should be taken from servlet by using ajax ...pls anyone help me ...



<HTML>
<HEAD>
<title>Add/Remove dynamic rows</title>
<SCRIPT lang="javascript">
function addRow(tableID)
{
var table = document.getElementById(tableID);

var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var counts = rowCount - 1;
var cell1 = row.insertCell(0);
var houseNo = document.createElement("input");
houseNo.type = "text";
houseNo.name = "houseNo";
cell1.appendChild(houseNo);
var cell2 = row.insertCell(1);
var street = document.createElement("input");
street.type = "text";
street.name = "street";
cell2.appendChild(street);
var cell3 = row.insertCell(2);
var city = document.createElement("input");
city.type = "text";
city.name = "city";
cell3.appendChild(city);
var cell4 = row.insertCell(3);
var country = document.createElement("input");
country.type = "text";
country.name = "country";
cell4.appendChild(country);
}
</SCRIPT>
</HEAD>
<BODY>
<form action="submit" method="post">
<table>
<tr>
<td>
Reg No
</td>
<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:</td>
<td><INPUT type="text" name="regNo" /></td>
</tr>
<tr>
<td>Name</td>
<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:</td>
<td><INPUT type="text" name="name" /></td>
</tr>
<tr><td><br/><b>Addresses</b></td>
</tr>
</table>
<TABLE id="addressesTable">
<TR>
<TD>House No</TD>
<TD>Street</TD>
<TD>City</TD>
<TD>Country</TD>
</TR>
<TR>
<TD><INPUT type="text" name="houseNo" /></TD>
<TD><INPUT type="text" name="street" /></TD>
<TD><INPUT type="text" name="city" /></TD>
<TD><INPUT type="text" name="country" /></TD>
</TR>
</TABLE>
<INPUT type="button" value="Add More" onclick="addRow('addressesTable')" />
<input type="submit" value="SUBMIT" />
</form>
</BODY>




Dynamic form validation in angularJS not working


I have created dynamic form, And adding the ng-required attributes dynamically to my controls. but now it's not working .


This is my JS :



var app = angular.module('birthdayToDo', []);

app.controller('main', function($scope){
$scope.Control={};
$scope.Attributes =[
{
"Name":"FirstName",
"Required":"true"
},
{
"Name":"LastName",
"Required":"false"
},
{
"Name":"Email",
"Required":"true"
},
{
"Name":"Age",
"Required":"false"
}];

$scope.submitForm = function(isValid) {

// check to make sure the form is completely valid
if (isValid) {
alert('our form is amazing');
alert($scope.Control[1]); // to check correct index
}else{
return;
}

};
});


And My HTML :



<html>

<head lang="en">

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" />
<script src="app.js"></script>

</head>

<body ng-app="birthdayToDo" ng-controller="main">
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<table>
<tr ng-repeat="attribute in Attributes">
<td>{{attribute.Name}}</td>
<td>
<input type="text" name="Control[$index]" ng-model="Control[$index]" ng-required="{{attribute.Required}}" />
</td>
<td>
<p ng-show="userForm.Control[$index].$error.required">{{attribute.Required == "true" && attribute.Name+' Required' || ''}}</p>
</td>
</tr>
</table>
<input type="submit" value="Save" />
</form>
</body>


Plunker Link


I want to show error message when either the textbox value change or form is submitted .


But when I'm doing same thing with static form it's working. working plunker





get valve of javascript variable and pass it to modal from view to get the list


I have 3 select dropdown fields Country,State,City.Onload of the page only country field is enabled (city and state fields are disabled)then if user select country then state field is enabled(with all the states mapped on that country stored in my database) then if user select state then city field is enabled(with all the city mapped on the on that state stored in my database).My dropdowns code are



<select class="form-login" id="country_id" onchange="setDropdownState();">
<option value="select" >Select country</option>
@for(country <- countryList) {
<option value="@country.getId" >@country.getName</option>
}
</select>
<select class="form-login" id="state_id" onchange="setDropdownCity();">
<option value="select" >Select country</option>
@for(state<- Country.findStateByCountryId(get value of cid from setDropdownState function)) {
<option value="@state.getId" >@state.getName</option>
}
</select>
<select class="form-login" id="city_id" >
<option value="select" >Select country</option>
@for(city<- State.findCityByStateId(get value of sid from setDropdownCity function)) {
<option value="@state.getId" >@state.getName</option>
}
</select>


scripts



$(document).ready(function() {
$("#state_id").attr("disabled", true);
$("#city_id").attr("disabled", true);
});

function setDropdownState() {
var cid = $("#country_id").val();
if (cid != "select") {
//pass value to state dropdown
$("#state_id").attr("disabled", false);
} else {
$("#state_id").attr("disabled", true);
$("#city_id").attr("disabled", true);
}


}

function setDropdownCity() {
var sid = $("#state_id").val();
if (sid != "select") {
//pass value to citydropdown
$("#city_id").attr("disabled", false);
} else {
$("#city_id").attr("disabled", true);
}
}


So I have to pass country_id value onchange of country select box to get state field for loop value Country.findStateByCountryId(get value of cid from setDropdownState function) and in the same way pass state_id on change of state field to city field for loop to get the desired city on that particular state State.findCityByStateId(get value of sid from setDropdownCity function).


So how can I pass javascript value to model??


Is It possible??


Or is there any other way to do this??


Thanks





JQUERY refill while emptying


I'm trying to smoothly reload this div. `


grabchart(userid, div); purpose is to fill the div with users data.



$( ".reload" ).click(function() {
if($("#line-example-refresh").is(':empty') && ($("#line-example:not(empty)"))) {
$( "#line-example" ).empty();
<?php echo 'grabchart('.$_COOKIE['uid'].',"line-example-refresh");';?>
}

if($("#line-example").is(':empty') && ($("#line-example-refresh:not(empty)"))) {

<?php echo 'grabchart('.$_COOKIE['uid'].',"line-example");';?>
$( "#line-example-refresh" ).empty();
}
});


What's happening here is that my script verify the first statement and then clear #line-example, then since it just cleared this div, it makes the second statement true. What i need is verify if one of twos statement is true then halt the script.





Implement Facebook API login with reactjs


I'm working on using Facebook's Javascript SDK for authentication. I've been able to import the SDK properly and put a Like button on my page. But, the facebook login button has to be wrapped in the tag:



<fb:login-button/>


I currently have all of the code from the Facebook Login tutorial pasted into my index.html, the only html file in my project, which houses the React application. But, I need to put the last part, which has the actual login button, into my React component. When I tried to do that, I got the following error:



ReactifyError: /Users/ritmatter/reps/js/components/Signup.jsx: Parse Error: Line 82: Unexpected end of input while parsing file: /Users/ritmatter/reps/js/components/Signup.jsx
sdk.js:61 The "fb-root" div has not been created, auto-creating
ping?client_id=894010190618709&domain=localhost&origin=1&redirect_uri=http%3A%2F%2Fstatic.ak.facebo…:1 Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.


How can I get the login button into react?





Overlapping Isotope images when adding images


I have been struggling to get Isotope to work. I have an application where after clicking a button I load some more images by getting their URLs from JSON. The issue I am having is that when I add the images to the 'galleryContainer' div (my div that I am holding all the images in) the images overlap. That or nothing happens and the whole page seems to freeze. Apparently this is a frequent problem but I still have not been able to get it working for my project. I try to use 'imagesLoaded' but it never seems to work for me.


Here is the relevant code:



// Get more images and add them to the galleryContainer
function getMoreImages() {
for (var i = 0; i < 3; i++) {
var newImage = $('<div class="objects"></div>');
var x = Math.floor((Math.random() * 750) + 750);
var y = Math.floor((Math.random() * 750) + 750);

newImage.append($('<img width="750" src="http://lorempixel.com/' + x + '/' + y + '">'));
$container.append(newImage).imagesLoaded(function() {
$container.isotope('appended', newImage);
});
}
}


Here is a (JSFiddle)[http://ift.tt/1tBbNHi] demonstrating my problem.


It is totally possible that I am simply making a simple mistake JS wise (like not using the imagesLoaded plugin correctly), since I am sort of new to it.


Thanks =)





How do I move a php call to another div and have it still work


I've looked around a bit, and found issues similar to mine, but not quite the same. I have a page template that is laid out in 4 columns in HTML. Inside column 4, I have a php function echoing a gallery of images.



<div id="homepage-layout">

<div id="homepage-column-1">
<div class="homepage-small"><?php echo get_homepage_img_small_1(); ?></div>
<div class="homepage-small"><?php echo get_homepage_img_small_2(); ?></div>
<div class="homepage-small"><?php echo get_homepage_img_small_3(); ?></div>
</div><!-- End Column 1 -->

<div id="homepage-column-2">
<div class="homepage-large-left"><?php putRevSlider("homepage"); ?></div>
</div><!-- End Column 2 -->

<div id="homepage-column-3">
<div class="homepage-med"><?php echo get_homepage_img_med_1(); ?></div>
<div class="homepage-med"><?php echo get_homepage_img_med_2(); ?></div>
</div>

<div id="homepage-column-4">
<div class="homepage-large-right"><?php putRevSlider("home_small"); ?></div>
</div><!-- End Column 4 -->

</div>


I'm using jQuery to change the layout of the site based on the width of the window.



var column3 = $("#homepage-column-3").contents();
var column4 = $("#homepage-column-4").contents();
var swapped = false;

$(window).on('resize', function() {
if( $(window).width() <= 700 && !swapped){
$("#homepage-column-3").html(column4);
$("#homepage-column-4").html(column3);
swapped = true;
} else if( $(window).width() > 700) {
$("#homepage-column-3").html(column3);
$("#homepage-column-4").html(column4);
swapped = false;
}
});


However, when the window size triggers the jQuery, the RevSlider from Column 4 freezes on the image it was displaying at the time, and the only way to get it running again is to refresh the page.


Any thoughts? Or, if this question has been answered already, please point me in the right direction.


Thanks!





how access magento ProductConfigure.spConfig


I'm trying to load extra information for new orders thru javascript on admin area. I need to get the spConfig info from other script. but, I can't find how can access it. the file I'm using to load it is the /adminhtml/default/default/template/catalog/product/composite/fieldset/configurable.phtml



<script type="text/javascript">
var config = <?php echo $this->getJsonConfig() ?>;
if (window.productConfigure) {
config.containerId = window.productConfigure.blockFormFields.id;
if (window.productConfigure.restorePhase) {
config.inputsInitialized = true;
}
}
ProductConfigure.spConfig = new Product.Config(config);
</script>


any help would be great! thanx!





How to convert string to date format


I have string format data like below



Dec 26, 2014, 09:56 ET
Dec 31, 2014, 21:30 ET
Dec 30, 2014, 13:36 ET


And i want output in the below date format



26-12-2014 09:56:00
31-12-2014 21:30:00
30-12-2014 13:36:00


I have tried with the below code but it is giving different values. Correct me which syntax i can apply to convert string to date



str2date(input,"MMM dd, YYYY, HH:mm 'ET'")




Relative ui-router templateUrls in Ionic vs vanilla AngularJs


I'm using angularJs to create a SPA and using the same angularJs code to create an ionic app.


So far this has been an extremely straight forward process but now I have conflicts between AngularJs expecting me to use absolute urls:



templateUrl: "/views/login.html",


And Ionic expecting me to use relative urls:



templateUrl: "views/login.html",


I've explored 2 workarounds that I'm not satisfied with.


Option 1:



var isIonic = window.ionic ? true : false;
var baseUrl = "/"

//templateURL paths must be relative for ionic
if(isIonic){
baseUrl = "";
}

....

templateUrl: baseUrl + "views/login.html",


Option 2, In my index.html file:



<head>
....
<base href="/">


And then I leave the base tag out in my ionic html file.





  • Option #1 works fine but the number of directives used turns this into an if/else nightmare

  • Option #2 works great in all browsers but it breaks my SVGs in Firefox.


Does anyone know of a better solution to handling templateUrls when angularJS in a web browser expects absolute paths, and ionic on a mobile device expects relative paths?





Meteor: Tracker.autorun isn't running on user collection change?


I'm using this package to manage Facebook data as Collections in Meteor. Since a FacebookCollection can't be defined until the user is logged in with Facebook, this ticket describes a method to do so automatically; I've been trying it like so:


/lib/collections.js



Tracker.autorun(_.bind(function(){
var user = this.user;
if (user && user.services && user.services.facebook && !Friends){
Friends = FacebookCollections.getFriends("me",["id","name"],100);
}
}),this);


Using some log statements, I see this run only once, early on when user is still undefined, but never again. I suspect that this isn't being re-run because it's not referencing a reactive data source, i.e. the User collection, but I'm not quite sure what to do here to get this to work.


Note: the example in the ticket uses Meteor.user(), however, this gives the error: Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.





how to control the scene size?


I have set up a test scene where the camera can be moved with the arrow keys, left and right keys rotate on the y axis and up down moves forward or backward on the z axis, makes like driving. Have a ground and sky set up as plains. Problem I got is after I move so far the sky and ground disappear and all I can see is white, like I ran off the scene. Is it possible to make the scene or map area bigger so I can go farther without running off the scene or map.


thanks in advance,


mike.





How to select specific string [on hold]


I'm getting object like this:



'type' = "CustomContact"
'category' = "Category 111"
'phonenumber' = "2222"
'firstname' = "Mickey Mouse"


How can I select category as category, phonenumber as number string in jQuery?





Node.js: How to run asynchronous code sequentially


I have this chunk of code



User.find({}, function(err, users)
{
for (var i = 0; i < users.length; i++)
{
pseudocode
Friend.find({'user':curUser._id}, function(err, friends) **ANOTHER CALLBACK**
{
for (var i = 0; i < friends.length; i++)
{
pseudocode
}
console.log("HERE I'm CHECKING " + curUser);
if (curUser.websiteaccount != "None")
{
request.post({url:'blah', formData: blah}, function(err, httpResponse, body){ **ANOTHER CALLBACK**
pseudocode
sendMail(friendResults, curUser);
});
}
else
{
pseudocode
sendMail(friendResults, curUser);
}
});
console.log("finished friend");
console.log(friendResults);
sleep.sleep(15);
console.log("finished waiting");
console.log(friendResults);
}
});


There's a couple asynchronous things happening here. For each user, I want to find their relevant friends and concat them to a variable. I then want to check if that user has a website account, and if so, make a post request and grab some information there. Only thing is, that everything is happening out of order since the code isn't waiting for the callbacks to finish. I've been using a sleep but that doesn't solve the problem either since it's still jumbled.


I've looked into async, but these functions are intertwined and not really separate, so I wasn't sure how it'd work with async either.


Any suggestions to get this code to run sequentially?


Thanks!





Boolean disjunction (OR) using mocha and chai


I have the following scenario in which I have to check that an URL was build correctly provided some query arguments. I do not expect the system to apply an specific order in the rendered URL, so I came with the following test case which I expected to work:



it('test that url is built correctly', function () {
var args = {
arg1: 'value1',
arg1: 'value2'
};

var rendered_url = render_url(args);

expect(rendered_url).to.equal('/my/url?arg1=value1&arg2=value2')
.or.to.equal('/my/url?arg2=value2&arg1=value1')
;
});


I was pretty surprised to the or chain to not exists as it makes the statement construction process tidy and cozy.


I know I can workaround this in many ways (for example, using satisfy), but I wonder:



  • Whether I cannot find the pattern to achieve in a similar way what I want in the documentation(I have read it thoroughly)...

  • ... or whether there exists a good reason to not include this construction in chai...

  • ... and whether there exists any other library or script that provides that feature.





crossrider extension won't load on https websites


I'm using crossrider to make a cross-browser extension for my website.


Here's my Page Code (extension.js) :





appAPI.ready(function($) {


//alert("Hello World");
appAPI.resources.createImage(
'<a href="test.html"><img src="http://localhost/images/fleche.png" width="128" height="128" /></a>'
).prependTo('body');

});



The snippet is only working with website using the http protocol. When it comes to https, the javascript code doesn't run.


Thank you for your help.





In early versions of JavaScript, what was the reasoning behind having the context default to the global object? [on hold]


In early versions of JavaScript, what was the rationale behind having the context default to the global object?



function a() {
console.log(this); //window
}




pdf.js failing on getDocument



  • browser: Chrome

  • environment: grails app localhost


I'm running a grails app on local host (which i know there's an issue with pdf.js and local file system) and instead of using a file: url which i know would fail i'm passing in a typed javascript array and it's still failing. To be correct it's not telling me anything but "Warning: Setting up fake worker." and then it does nothing.



PDFJS.disableWorker = true; // due to CORS

// I convert some base64 data to binary data here which comes back correctly
var data = utilities.base64ToBinary(result);

PDFJS.getDocument(data).then(function (pdf) {
//nothing console logs or reaches here
console.log(pdf);
});


I'm wondering if I just don't have it set up correctly? Can I use this library purely on the client side by just including pdf.js or do I need to include viewer.js too? and also i noticed compatibility file... the set up isn't very clear and this example works FIDDLE and mine doesn't and I'm not understanding the difference. Also if I use the url supplied in that example it also says the same thing.





Node.js MongoDB returning 0 documents while write lock is in place


I have a simple node server running that queries mongoDB and returns documents to the client for processing. In the background, I have a java application that's capturing data from various sources and writing to the mongoDB instance as a batch process. The java app also updates records in the mongoDB instance as appropriate. The java app does this approximately once per minute, and usually includes about 500 inserts and maybe 1000 updates.


Node.JS:



var MongoClient = require('mongodb').MongoClient;
var collection = '';
MongoClient.connect('pathToMongo', function(err, db){
collection = db.collection('mycollection');
});
...
app.get('/getData', function(req, res){
collection.find(queryString, {_id: 0, createdAt: 0}).sort({EVENTTIME:-1}).toArray(function(err,docs){
if (err){
console.log(err);
res.send(500,err);
} else {
res.json(docs);
}
});
});


Java snippet (assuming I already have all my data to insert/update in result and a valid connection to mongoDB):



public static void doWork(DBCollection coll){
while(result.next()){
BasicDBObject tempDoc = new BasicDBObject();
//Add values to tempDoc based on result iteration
DBObject unchanged = coll.findOne(tempDoc);
if (unchanged != null){
//update existing record
DBObject modifiedObject = new BasicDBObject();
modifiedObject.put("$inc", new BasicDBObject().append("cyclesUnchanged", 1));
coll.update(unchanged, modifiedObject, false, false);
} else {
//insert record
coll.insert(tempDoc);
}
}
}


Initialization of the java Mongo instance:



MongoClient mongoClient;
DB db;
DBCollection coll = null;
try{
mongoClient = new MongoClient('localhost", 27017);
db = mongoClient.getDB("test");
coll = db.getCollection("mycollection");
} catch (Exception e){
System.out.println("Mongo Error.");
System.exit(0);
}
final DBCollection newColl = coll;
doWork(newColl); //call to method above


My node server returns the exact number of documents I'm expecting most of the time (so it's not a query issue). However, occasionally, the query will run into a write lock (verified with db.currentOp() on mongod AND db.collection('$cmd.sys.inprog').findOne on the Node.js server), and return 0 documents. This is an issue, as I'm using this count for metrics, and need some sort of a method to ensure integrity of my query (which could be 0 documents). Is there something in Node.js's mongoDB package that attempts to retry if a write lock is in place?


I'm running MongoDB v2.6, mongo java driver v2.12.3, and Node.js v0.10.29.


UPDATE 12/31/2014:


The mongoDB query I'm using (referenced as 'queryString' above):



[{"$or", [{"PRI":{"$gte":"1","$lte":"9"}}]},{"EVENTTIME":{"$gte":"2014:12:31::16:59:18"}}]


I should note that this query, 99% of the time, works flawlessly. I'll have instances where I return 12 documents, as expected, every minute, for hours. And then, for some reason (I'm assuming a write lock is preventing reads), I'll get 0 documents returned.


The "sometimes appearing" currentOp (which is just an insert):



"opid" : 71715202,
"active" : true,
"secs_running" : 0,
"microsecs_running" : NumberLong(251),
"op" : "insert",
"ns" : "test.mycollection",
"insert" : {
"_id" : ObjectId("54a429a2880cc7fb7d2236465"),
"altID" : "999999",
"PRI" : "9",
"EVENTTIME" : "2014:12:31::17:55:12",
"LAT" : "0",
"LON" : "0",
"createdAt" : ISODate("2014-12-31T16:51:46.250Z")
},
"client" : "127.0.0.1:60750",
"desc" : "conn171",
"connectionId" : 171,
"locks" : {
"^" : "w",
"^test" : "W"
},
"waitingForLock" : false,
"numYields" : 0,
"lockStats" : {
"timeLockedMicros" : {

},
"timeAcquiringMicros" : {
"r" : NumberLong(0),
"w" : NumberLong(3)
}
}




title bar in javascript pop-up window with div and css instead of table


I am replacing the showModalDialog function in several web applications. A javascript function was made using two overlays: one masks all content on the page, and the other shows pop-up content. Because some pages invoke showModalDialog two or three times, the javascript replacement manages multiple calls by doing new overlays over what is already there. It works well in Chrome, IE, and FF.


But I want the pop up content to be more in the form of a window with a title bar, because I like windowing. It is easy to thread popped-up content. Since underlying content is masked, nothing beneath can be acted upon, and only popped-up content can be acted upon. The javascript function has several parameters such as whether to mask underlying content, whether to use a border, etc. To fully replicate showModalDialog I want the function to return a value in addition to displaying content. I want the function to add a submit button, optionally, but instead of a cancel button I want a title bar with a big X or reverse-color square.


Finally to the question, how do I make a title bar with an X or square at one end, without using a table? We have screen readers and applications need to meet accessibility standards. Tables in a page are more difficult for people using screen readers and should be avoided when possible. The title bar will have the same border color passed to the function as an argument, or black default. Thanks





Jquery - $.GET Place In Closest Div


So this is probably very easy but for some reason I can't get it to work. I have a $.get function that runs properly. I want the data/results to load into the closest div. When I identify the div specifically, everything works fine:



$.get( lk, function(data) {
$("div.tcontainer").html(data);
});


But when I try to look for the closest div, it does not work. I have a few divs on the page (dynamically) and they have the same attributes so i need to find the closes div and load the data like:



$.get( lk, function(data) {
$(this).closest("div.tcontainer").html(data);
});


But this does not work. Can someone help me find the closest div using the code above. Thank you.





CSS make div fill remaining space of parent element


how can I make a div fills the remaining space (height) of the parent? Here are my code snippets: html



<div id="mainWrapper">
<div id="header">...
</div>
<div id="contentWrapper">
<div id="content">
</div>
</div>

</div>


css



#mainWrapper
{
width: 900px;
height: 100vh;
margin-left: auto;
margin-right:auto;
padding-top:100px
}
#header{
height:456px;
}
#contentWrapper{
background-color:black;
padding: 30px;
overflow: auto;
height:100%;
}


The contentWrapper should fill all the ramining space below the header. Large content should be scrollable and not change contentWrappers height. I tried a lot what I found on google but nothing helped me, yet.. Is there a solution using pure css or do I have to use JS instead?


regards





IE Developer Tools breakpoints are not working


I'm trying to debug some javascript in IE 11 and I'm not able to force it to stop on a breakpoint.


debugger; line works fine (stops debugger in that line), same file without a debugger; line but with a breakpoint set in the same place does nothing (function works fine, but debugger does not stop on a breakpoint).


Chrome's and Firefox's debuggers stop on breakpoints in the same places.


Any thoughts what could be the cause of this behavior?





how to add attribute to tags in CKEDITOR?


I need that my link will have attribute vfoto='advert'. example: <a href='#' class='link' vfoto='advert'><img src='/pick.png'/></a>. how to relize that ..? what the files to edit ? thanks .. P.S i live in Ukraine . Please russian speak if you can .





why encapsulate functions within $()


I'm taking Udacity's "javascript design patterns" and I stumbled upon a code that calls jQuery's object like described below:


In retain.js file (http://ift.tt/1y6Nj9U), the code starts with a call to the jQuery object "$()". Inside it, we can find the Model-Octopus-View declared and initialized.


I don't get why it resides inside the jQuery object and I also don't get how do we get access to it during the life of the application. E.g., I tried to manipulate it through the console, to no avail.





What is the usage of the backtick symbol (`) in JavaScript?


A backtick seems to work the same as a single quote symbol, so I could use it to define a string like this:



var s = `abc`;


Is there any way in which the backtick actually differs from a single quote?





LinkedIn Share button breaks Bootstrap Modal


We recently added the LinkedIn share button to a site of ours with Bootstrap. After some testing, we realized this script, http://ift.tt/IX0rQc, overwrites (at the very least) the Bootstrap functionality for the modals. I don't know if it overwrote any of its other functionality, because we were only looking at the modals.


Is LinkedIn aware of this issue, and is their a solution to the problem?


Update:


Yes, I was sent here by Linked-in. After posting to their forum, I was directed here by who I think is a site admin.


Here is some code:



<div class="modal fade" id="BlogEmail" role="dialog" aria-hidden="true">
****Modal content****
</div>


Nothing special, just a simple Bootstrap modal. And the trigger to open:



<a href="#" title="Subscribe by email"><i class="fa fa-envelope-o rl-blog-icon" data-toggle="modal" data-target="#BlogEmail"></i></a>


This works fine, as intended, until adding the Linkedin script. Once this is added:



<script src="//platform.linkedin.com/in.js" type="text/javascript">
lang: en_US
</script>


The Modal functionality breaks. Typing the following in the console:



$("#BlogEmail").modal();


or



$("#BlogEmail").modal('show');


throws:



TypeError: undefined is not a function



The above does work when the Linked-in js is not included.


Another update:


I downloaded the file, http://ift.tt/IX0rQc, and found this:



$_CONSTANTS.modes


and is used in this capacity (this is assigned to multiple vars/objects multiple times)



d=$_CONSTANTS.modes;


and the conflict



d.modal


$_CONSTANTS is defined here:



http://ift.tt/1y6NiCN


so I downloaded this, and overrode it so it loaded my version.


and on line 830



(function(){$_CONSTANTS={ ... modal:"modal" ... };


so I replaced all property references from modal to modals in both files


this causes these two lines to break, on line 1172, so I commented them out



IN.Event.on(window,b.beforeUnload,$_STATISTICS.firePing);
IN.Event.on(window,b.unload,$_STATISTICS.firePing)


The sharing now works but the Bootstrap modal is still broken.


Going back to unmodified files,


The Bootstrap code that breaks is :



var manager = typeof this.options.manager === 'function' ?
this.options.manager.call(this) : this.options.manager;

manager = manager.appendModal ?
manager : $(manager).modalmanager().data('modalmanager');

manager.appendModal(this);


I'm beginning to redefine the class definition of Modal to Modals, to see if I can get the conflict to go away, since the Bootstrap's code is more manageable. I'll update with what I find.





Android (5.0.1) Chrome is deleting javascript whitespace and comments, is there a way to stop this?


In addition to making debugging almost impossible, this new behavior is breaking my website where I use the heredoc javascript technique, (Javascript heredoc) which depends on using comments.


I'm not sure if I inadvertably turned this on, and this is a rare occurrence, or if this is a new Android feature. I'm concerned because I use the heredoc javascript technique on a number of different sites, and this behavior will break these sites.


Has anyone else experienced this?


Is there a workaround where the server can stop this?


Is there an alternative to the heredoc javascript technique?





What is causing an "Error connecting to native app" when connecting to a native host application with connectNative() in a Chrome extension?


I am implementing communication between a web page and a Mac application using Chrome's Native Messaging feature. All seems to go well until I make the javascript call to chrome.runtime.connectNative("my_native_host_app_name"), which produces the following error in the console:



Error in event handler for runtime.onMessageExternal: Error connecting to native app: com.allinlearning.nmhforbrowserextension
Stack trace: Error: Error connecting to native app: com.allinlearning.nmhforbrowserextension
at Object.<anonymous> (extensions::runtime:189:11)
at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at Object.handleRequest (extensions::binding:55:27)
at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at Object.<anonymous> (extensions::binding:318:32)
at chrome-extension://gldheanjpgopipommeingjlnoiamdfol/background.js:19:27
at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at EventImpl.dispatchToListener (extensions::event_bindings:395:22)
at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
at Event.$Array.forEach.publicClass.(anonymous function) [as dispatchToListener] (extensions::utils:65:26) extensions::event_bindings:383
EventImpl.dispatch_extensions::event_bindings:383
EventImpl.dispatchextensions::event_bindings:401
$Array.forEach.publicClass.(anonymous function)extensions::utils:65
messageListenerextensions::messaging:190
EventImpl.dispatchToListenerextensions::event_bindings:395
$Array.forEach.publicClass.(anonymous function)extensions::utils:65
EventImpl.dispatch_extensions::event_bindings:378
EventImpl.dispatchextensions::event_bindings:401
$Array.forEach.publicClass.(anonymous function)extensions::utils:65
dispatchOnMessageextensions::messaging:304


The actual call that seems to cause this error (line 19 in the ref to background.js in the stack trace) is:



port = chrome.runtime.connectNative("com.nmhforbrowserextension");


To give more context, it is invoked from a listener:



chrome.runtime.onMessageExternal.addListener(

function(request, sender, sendResponse) {
//var imgdata = JSON.stringify(request.imgdata);
//process it somehow here

port = chrome.runtime.connectNative("com.allinlearning.nmhforbrowserextension");

if (port)
console.log("connectNative() returned a non-null port");
else
console.log("connectNative() returned null for the port");
});


It never gets to the if statement. The doc I am primarily using is Chrome Native Messaging. At the bottom of the doc it has a section to provide help with common errors Debugging native messaging. I can't seem to relate the "Error connecting to native app" to any of the specifically mentioned errors.


The complete contents of my extension manifest file ("manifest.json") are:



{
"manifest_version": 2,

"name": "AIL Extension",
"version": "1.0",
"description": "New Reader",

"background": {
"scripts": ["background.js"]
},

"externally_connectable": {
// Extension and app IDs. If this field is not specified, no
// extensions or apps can connect.
"ids": [
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
],
// Match patterns for web pages. Does not affect content scripts.
// If this field is not specified, no webpages can connect.
"matches": [
"http://localhost/charles/qrexttest/*"
],

"permissions": [
"nativeMessaging",
"tabs",
"activeTab",
"background",
"http://*/", "https://*/"
],

// Indicates that the extension would like to make use of the TLS
// channel ID of the web page connecting to it. The web page must
// also opt to send the TLS channel ID to the extension via setting
// includeTlsChannelId to true in runtime.connect's connectInfo
// or runtime.sendMessage's options.
"accepts_tls_channel_id": false
}
}




Disable js on certain link tag


Hi there and happy new year,


I have a menu which uses the scrollto plugin ( * http://ift.tt/p0GPZL).


My Page is a onePager and every menu item click, scrolls to a specific area.


I wanna disable this function (or any js) on certain a tags like this:


<a href="http://www.test.com" onclick="// disable js on this tag"> But I have no idea how to do this.


I only know that something like this $(self).preventDefault should do that stuff.


Can someone help me out with a oneliner?


Thank you!!!!!





Div with two divs inside the same size (img inside)


I am trying to have a div with an image be on the same line as another div that allows other divs to be be stacked on top of each other in the right side?


Here is an image I created with what I am trying to achieve. Thank you: http://ift.tt/1x4xtuV



<div class="media">
<div style="display:inline">
<img src="images/sample.png" width="92px" height="135px" >
<div>
<div style="display:inline;" > Points: 1422</div>
<div style="display:inline;"> Level: 17</div>
<div style="display:inline;">
<img src="images/experienceBar.png" >
</div>
</div><!-- End div .media -->




How to change namespace in moment js?


I'm trying to change namespace for moment js. The script wrapped (function (undefined) {...}).call(this); I could pass namespace in call, however that breaks bower update compatibility (bower would override my change, and I could forget to keep files in sync). Can you suggest alternative solution?


Documentation suggest to use require.js to pass configuration options.http://ift.tt/1pjcgXN It's an additional script that I have to load. Is there alternative to require.js?


moment js has a makeGlobal function:



function makeGlobal(shouldDeprecate) {
/*global ender:false */
if (typeof ender !== 'undefined') {
return;
}
oldGlobalMoment = globalScope.moment;
if (shouldDeprecate) {
globalScope.moment = deprecate(
'Accessing Moment through the global scope is ' +
'deprecated, and will be removed in an upcoming ' +
'release.',
moment);
} else {
globalScope.cplex = {};
globalScope.cplex.moment = moment;
}
}


I combine and minify js with make. One solution that's not ideal:



//moment-init.js
var ender = undefined;
if(typeof moment !== 'undefined'){
var existingMomentJs = moment;
}
//load moment script
//moment-overrider.js
//updating namespace for moment js - abc namespace
var abc = {};
var ender = undefined;
abc.moment = moment;
if(typeof existingMomentJs !== 'undefined'){
moment = existingMomentJs;
}




Address validation with Google Geocode API


I have worked out getting part of my code to work properly but I am stumbling on getting the second stage of it to work. With the code below I am performing a US ZIP code validation through Google Geocode API and if valid I am auto populating a form field with the assigned city for that zip code. But I am trying to to get the function to run recursively or however else it needs to run to perform another validation against the street address entered into the form field. If it validates then nothing should happen, if the street address doesn't validate then user is presented an alert box just like the zip/state alert box on fault.


It seems that when Google cannot validate a numeric address but other information pushed to the API is verifiable, Google tries to respond with the closest approximation and the ITEM TYPE in the JSON response is "route" (Which is what I want to use to evaluate a non resolvable address) - a successful response returns a item type of "street_number"


How can I get the numeric address verification portion of the code to work?


HTML (Code minimized)



<?php include ('addverify.php'); ?>

<div style='margin-top:5px;' class='rt'><label> Service Address: </label><input id='saddr' name='saddr' type='text' class='rounded' style='width:230px' required placeholder='Numeric and street name'></div>
<div style='margin-top:5px;' class='rt'><label> Service City: </label><input id='scity' name='scity' type='text' class='rounded' style='width:230px' required></div>
<div style='margin-top:5px;' class='rt'><label> Service State: </label><select id='sstate' name='sstate' class='rounded' style='width:230px' required>
<option value='AL'>Alabama</option>
<option value='AK'>Alaska</option>
</select></div>
<div style='margin-top:5px;' class='rt'><label> Service Zip: </label><input id='szip' name='szip' type='text' maxlength='10' class='rounded' style='width:230px' required placeholder='Service Zip Code' onBlur='codeAddress()'></div>


addverfy.php (Javascript inclusion)



<script src='http://ift.tt/1lrRXYd'></script>
<script>
var geocoder;
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById('szip').value;
//var address = encodeURIcomponent(document.getElementById('saddr').value);
alert (address)
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {

for (var component in results[0]['address_components']) {
for (var i in results[0]['address_components'][component]['types']) {
//if (results[0]['address_components'][component]['types'][i] == 'route') { alert ('Unable to validate street address');return;}
if (results[0]['address_components'][component]['types'][i] == 'country') {
country = results[0]['address_components'][component]['long_name'];
if (country == 'United States') { document.getElementById('scity').value=results[0]['address_components'][1]['long_name'];} else {alert('Non US Zipcode');}
}
if (results[0]['address_components'][component]['types'][i] == 'administrative_area_level_1') {
state = results[0]['address_components'][component]['short_name'];
document.getElementById('sstate').value= state;
//alert (document.getElementById('sstate').value)
}

}
}


} else { alert('Data error with Google, try again'); }
});
}

</script>


Valid address resolution JSON response


Unresolvable address resolution JSON response





Pebble App Message


I am creating a Pebble Watch app where you press a button and it sends a message to a contact you configured when you press the select button. I have the configuration page working, but I need help trying to send a text message from the watch. I am aware you can request information from a website or your phone, but I do not know how to do this so I can send my watch message. I am using pebble JS and developing on cloudpebble on windows 8 (if that matters). Is there a way I can send a text from my watch using JS? Thanks





Add to Apache logfile when user leaves webpage


I want to time how long a visitor spends on each page of my website by downloading and analysing the "ex" log file created daily by Apache in the logfiles folder.


I can do this when they move from one page to another but if someone visits the homepage and then leaves I have no idea how long they spent on it.


Could I somehow use Javascript's OnBeforeUnload event to request a file from the server, which would then appear in the log?





Angular Directive DOM manipulation behavior


I'm having some unexpected behavior with DOM manipulation in a directive. I have two icons and would like icons, a phone and email and would like to show their contents when hovered over. Which should be simple enough but I'm having trouble traversing the DOM to reach the child elements.


Here's my Directive:



app.directive('contact', function () {
return {
restrict: 'E',
scope: {
email:'@',
phone: '@',
extension: '@'
},
link: function (scope, element, attrs) {
var el = element;
var kids = $(el).children();
var emailChild = $(kids[0]);
var email = emailChild.context.children[0];

element.children().bind('mouseenter', function() {
console.log(this);
console.log(emailChild.context.children[0]);
console.log(email);
});
},


template: '<div class="contact_methods">' +
'<div ng-if="email" class="email" href="#">' +
'<div class="contact_info_email more_info" style="display:none;"><a ng-href="mailto:{{email}}">{{email}}</a></div>' +
'</div>&nbsp;&nbsp;' +
'<div ng-if="phone" class="phone" href="#"> ' +
'<div class="contact_info_phone more_info">{{phone}} ext.{{extension}}</div>' +
'</div>' +
'</div>'


}

});


Here is the unexpected behavior:



console.log(this);
console.log(emailChild.context.children[0]);
console.log(email);


These evaluate to:



<div class=​"contact_methods">​…​</div>​
<div ng-if=​"email" class=​"email ng-scope" href=​"#">​…​</div>​
undefined


email outputs undefined; however, it's contents are the line above it? Also I am unable to drill down into it like element.children().children()? The hover stops working.





How to add a class for html tag () depending a condition with javascript


I need to add style classes according to the number of <span> in a <li> I start with the following code:



$(document).ready(function() {
var ul = document.getElementsByTagName("ul");
for (var i, li; li = ul.childNodes[i]; i++) {
if (li.tagName == 'LI') {
var container = li.getElementsByTagName("span");
var nb = container.length;
if (nb == 1)
{
container[0].childNodes[0].setAttribute("class", "class1")
}
else if (nb == 2)
{
container[0].childNodes[0].setAttribute("class", "class2")
container[0].childNodes[1].setAttribute("class", "class3")
}
}
}});


JsFiddle Example





lundi 29 décembre 2014

Draw Google Charts using XML data


I am using Google Charts to draw a chart. The data source is getting from Google SpreadSheets. I want it to get from an XML file instead of GoogleCharts. The source code is in the below.



<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
var visualization;

function draw() {
drawVisualization();
drawToolbar();
}

function drawVisualization() {
var container = document.getElementById('visualization_div');
visualization = new google.visualization.PieChart(container);
var vartest = new google.visualization.Query('https://spreadsheets.google.com/tq?key=pCQbetd-
CptHnwJEfo8tALA').
send(queryCallback);
}
function queryCallback(response) {
visualization.draw(response.getDataTable(), {is2D: true});
}

google.setOnLoadCallback(draw);
</script>
</head>
<body>
<div id="visualization_div" style="width: 570px; height: 500px;"></div>
<div id="toolbar_div"></div>
</body>
</html>


Now you can see vartest variable query gets data from the https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA. Data within this URL is in the below.



// Data table response
google.visualization.Query.setResponse({"version":"0.6","status":"ok","sig":"598319012","table":{"cols":[{"id":"A","label":"Element","type":"string","pattern":""},{"id":"B","label":"Percent","type":"number","pattern":"#0.###############"}],"rows":[{"c":[{"v":"iron"},{"v":32.1,"f":"32.1"}]},{"c":[{"v":"oxygen"},{"v":30.1,"f":"30.1"}]},{"c":[{"v":"silicon"},{"v":15.1,"f":"15.1"}]},{"c":[{"v":"magnesium"},{"v":13.9,"f":"13.9"}]},{"c":[{"v":"sulfur"},{"v":2.9,"f":"2.9"}]},{"c":[{"v":"nickel"},{"v":1.8,"f":"1.8"}]},{"c":[{"v":"calcium"},{"v":1.5,"f":"1.5"}]},{"c":[{"v":"aluminium"},{"v":1.4,"f":"1.4"}]}]}});


But what I want is instead of that URL the data must be in an XML stored within a web server and pull data from that.


But I cannot understand how to do that? Do I have to use AJAX?


Could someone help me to solve this matter?


Thanks and regards, Chiranthaka





Focus text input after toggling visibility (using AngularJS directives)


I need a <div> with a text <input> to be toggled visible and then focus on the text element.


Pressing a button sets two conditions to true, one to show the parent element, and another to focus the input element.


I'm using two custom directives:



  • The ng-visible directive toggles the visibility property (visible / hidden) when evaluated truthful.

  • The ng-focus directive focuses the element when evaluated truthful.




The problem I ran into is my directive tries to focus the element too soon (before the block has had enough time to display as visibility: visible) and thus the focusing fails. Quick test reveals if a 1 second long $timeout delay is added, it works fine.


How can I ensure the focus directive waits until its visible before trying to focus the element?




Minor note: I am aware of ng-show / ng-hide (which works in my testing), but I need to use the CSS visibility property here instead.




HTML



<button ng-click="showMe = true; focusMe = true;"></button>

<div ng-visible="showMe">
<input type="text" ng-focus="focusMe"/>
</div>


Visibility Directive



app.directive('ngVisible', function($animate) {
return {
restrict: 'A',
multiElement: true,
link: function(scope, element, attr) {
scope.$watch(attr.ngVisible, function(value) {
if( value === true ) {
$animate.addClass(element, 'visible', function() {
$animate.removeClass(element, 'invisible', function() {
scope.$apply();
});
});
} else {
$animate.addClass(element, 'invisible', function() {
$animate.removeClass(element, 'visible', function() {
scope.$apply();
});
});
}
});
}
}
});


Focus Directive



app.directive('ngFocus', function($timeout, $parse) {
return {
link: function(scope, element, attr) {
var model = $parse(attr.ngFocus);

scope.$watch(model, function(value) {
if(value === true) {
$timeout(function() {
element[0].focus();
});
}
});

// Set attr value to false on blur event so it can be refocused
element.bind('blur', function() {
scope.$apply(model.assign(scope, false));
});
}
};
});




Trouble with "mouseup" once DOM has been updated


I am writing a function that will be triggered every time I release the mouse(mouseup) from a inside a table row. This is accomplished using jquery: $('textarea').mouseup(function (e){ ...code }); Everything works fine except for when I add a new row to the table. Once I add the new row, i seems that the mouseup event is not detected. See the code in the link and do the following: 1. Write some text in the Col2 or Col3 2. Highlight the text. Expected: An alert will be shown with the text. 3. Press Add Row button, write something and highlight the text. The expected alert is not shown.


JsFiddle


Thanks!





Render a component within another in React


When a state is changed, React triggers componentDidUpdate() method, and by then I do:



componentDidUpdate: function () {
React.render(new SubmitButton, $('.uploader-submit').get(0));
}


As you saw, I'm rendering a SubmitButton when a specific state is changed, but my question is: is this the best behavior to get this feature done?


My scenario is: I'm uploading a photo. When the input[type=file] is changed, I create a new state property and then the componentDidUpdate() is triggered, invoking the SubmitButton.


This is my render() method:



render: function () {
return (
<div className="uploader">
<header className="uploader-header">
<div className="uploader-actions pull-left">
<div className="uploader-submit"></div>
<CancelButton router={this.props.router} />
</div>

<UploadButton callback={this.imageSelectedCallback} />
</header>

<Preview imageUri={this.state.imageUri} />
</div>
)
}


Couldn't I do something like the <Preview /> component? I mean, it is there, but something just appears when this.state.imageUri is different of null. This is the implementation of Preview:



var Preview = {
render: function () {
return (
<img src={this.props.imageUri} />
)
}
};

module.exports = React.createClass(Preview);


Yes, I know — "Preview" is invisible by default because it is an image, but I want to know if there's another approach to reach what I want: to show something based on a state, using the render method.





Can we build HTML5 Video Controls using Popcorn JS


I have a small issue with HTML5 Video Control and Popcorn JS. Actually my requirement is to build a seeking bar, play/pause, forward/backward controls using Popcorn JS for my video. I am bit confused which plugin to use for the above controls in Popcorn.


For my seeking bar there is an additional requirement. That is, whenever we hover on the seekbar, thumbnail image should be displayed. In that thumbnail we have to display some Image according to the location where we hover on that bar.


I am fed up with the RND of this requirement, can anybody please kindly solve my issue. The complete operations should be done by using Popcorn JS.


Thanks in Advance...





Parse.com / Javascript - Save users objectid string as user pointer


How do I save a user pointer to an object when i have the object id of the user.


I am able to save the object to the class in Parse but the assignee is always 'Undefined' in Parse.


e.g. I have retrieved the user object and can get the username / object id etc through:



function getUserFromUsername(username) {

Parse.initialize("...", "...");

console.log('The username passed in is: ' + username);

var User = Parse.Object.extend("_User");
var query = new Parse.Query(User);
query.equalTo("username", username);

query.first({
success : function(result) {
// Do something with the returned Parse.Object values
var userPointer = new Parse.User();
userPointer = result;
console.log(userPointer.get('username')); // this returns the correct username
return userPointer;

},
error : function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}


Which is called from my save task function below: (Note, I've logged all relevant fields and they return as expected.



function saveNewTask(clientName, taskTitle, taskDue, assigneeArray) {

Parse.initialize("...", "...");

var x;
for (x in assigneeArray) {

var Task = Parse.Object.extend("Tasks");
var task = new Task();

task.set("title", taskTitle);
task.set("date", taskDue);

var thisAssignee = GetUserFromUsername(assigneeArray[x]);
task.set('assignee', thisAssignee);

task.save(null, {
success : function(task) {
// Execute any logic that should take place after the object is saved.
console.log('New object created with objectId: ' + task.id);
},
error : function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
console.log('Failed to create new object, with error code: ' + error.message);
}
});
}


}





Why is my .bind not calling my function in javascript


!!! Found out that .apply does work. Consider this question solved.!!!


I know, by calling console.log, that my anime function in my animate function is being called repeatedly, like it should. I know that both my if statements in my anime function work properly by calling console.log, so my .bind should call my other functions, unfortunately it does not for some reason. My third function is my animate function, and the two functions that are being called through .bind are above it. I do have a blocks array, and it works properly and the blocks[i] does work properly, but that code is not posted to to keep out unnecessary details. I do have a KeyBlock constructor and objects created from it, but that code is also not posted for the same reason. My question is just why my .bind is not working in my if statements (the if statements work) in my anime function in my animate function. I need my .bind because my blocks[i] needs to be the this, when passed to another function from those functions that .bind calls.



KeyBlock.prototype.actorMove = function() {
var plusMinus = Math.floor(Math.random() * 2);
var plusMinus2 = Math.floor(Math.random() * 2);
if(plusMinus == 0)
var xNew = -1;
else
var xNew = 1;
if(plusMinus2 == 0)
var yNew = -1;
else
var yNew = 1;
KeyBlock.prototype.move.bind(this, xNew, yNew);
}
KeyBlock.prototype.playerMove = function() {
addEventListener("keydown", function(event) {
if(event.keyCode == 37)
xNew = -1;
if(event.keyCode == 38)
yNew = -1;
if(event.keyCode == 39)
xNew = 1;
if(event.keyCode == 40)
yNew = 1;
KeyBlock.prototype.move.bind(this, xNew, yNew);
event.preventDefault();
});
}
KeyBlock.prototype.animate = function() {
var time = Date.now();
var anime = function() {
for(var i = 0; i < blocks.length; i++) {
if((blocks[i]).type == "player") {
KeyBlock.prototype.playerMove.bind(blocks[i]);
} else {
KeyBlock.prototype.actorMove.bind(blocks[i]);
}
}
requestAnimationFrame(anime);
}
requestAnimationFrame(anime);
}'


thanks ahead of time :)





$http Cross Origin Request Blocked by Angular JS


I am trying to implement search suggestion using one of our Suggestions API "https://SuggestionsAPI.net/suggest?key=xyz" which is working fine with Ajax GET request but when I am trying to use it with Angular $http service, it is throwing me error is console:



Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote
resource at https://SuggestionsAPI.net/suggest?key=xyz. This can be fixed by moving the
resource to the same domain or enabling CORS.


Further I tried :



$httpProvider.defaults.headers.get = { 'Access-Control-Allow-Origin': '*' };
$httpProvider.defaults.headers.get = { 'Access-Control-Request-Headers': 'X-Requested-With, accept, content-type' };
$httpProvider.defaults.headers.get = { 'Access-Control-Allow-Methods': 'GET, POST' };
$httpProvider.defaults.headers.get = { 'dataType': 'jsonp' };


I am stuck here thinking why same GET request is blocked by browser when using Angular JS. Please suggest me to eliminate it.





CTRL key and arrow keys allow in input



<input type="text" id="s" />
jQuery('#s').bind('keyup blur',function()
{
var selectedInput = jQuery(this);
selectedInput.val( selectedInput.val().replace( /[^a-zA-Z0-9,]/g, '' ) );
});


I want to edit my text from anywhere in the text so I want the arrow keys (left,right,up,down) and plus crtl key to select all the text with ctrl+A.





How to modify the DOM directly in ReactJS


Let's say I have two arrays selectedFoobars and unselectedFoobars. These are my data and they are rendered as lists next to each other using ReactJS.


When the user clicks on an element in one of the lists I want to remove the element from that list, and add it to the end of the other list. That part is pretty straight forward using React.


But, I want the clicked element to sweep across the screen from its old position to its new position in the other list. If the user clicks on and element in the middle of the unselectedFoobars that element should animate across the page to the bottom of the selectedFoobars list.


I don't just want the moved element to fade out it the first list and fade in in the second. That would have been easy though, by using the animation hooks provided the the animation addon for React.


That is one – as far as I can tell – valid example of a problem where one needs to modify the DOM directly to achieve the desired result.


Using Backbone.js one could easily do the DOM manipulation manually. This is straight forward and pretty clean in Backbone-world albeit quite but a bit of work. In AngularJS I'd create a directive. It would be pretty unidiomatic Angular. But it would get the job done.


What is the cleanest way to handle this and similar cases where direct DOM manipulation is needed using ReactJS?