Alternate for isNaN() javascript function in Facebook? - facebook

I was using isNaN function in a Facebook application, but it was not working. the code that i was using
<script type="text/javascript">
<!--
function postValid(form)
{
var values=document.getElementById("phone").getValue();
if(isNaN(values))
{
var myDialog = new Dialog(Dialog.DIALOG_POP);
myDialog.showMessage('Almost Done!', 'Correct Mobile Numbers', button_confirm='Close');
}
else
{
var myDialog = new Dialog(Dialog.DIALOG_POP);
myDialog.showMessage('Almost Done!', 'Please Enter Correct Mobile Numbers Please', button_confirm='Close');
}
}
//-->
</script>
I have also used Regular expression but not working is there any alternative? or method by FBJS?

Yeah i got the Solution,
<script type="text/javascript">
<!--
function postValid(form)
{
var params=form.serialize();
var values=document.getElementById("phone").getValue();
var numericExpression = /^[0-9]+$/;
if(numericExpression.test(values))
{
if(values.length != 10)
{
var myDialog = new Dialog(Dialog.DIALOG_POP);
myDialog.showMessage('Almost Done!', 'Enter 10 Digits', button_confirm='Close');
return false;
}
else
{
return true;
}
}
else
{
var myDialog = new Dialog(Dialog.DIALOG_POP);
myDialog.showMessage('Almost Done!', 'Please Enter Correct Mobile Number Please', button_confirm='Close');
return false;
}
}
//-->
</script>
we can use the Regular expression earlier i used the element.value.match(numericExpression) method which didnt work. if you have any other solution please post so that we can get a better solution.

Related

Load more products not working in porto theme magento 2 on category page

I want infinite scrolling of product on category page but load more not working. I'm using porto theme.
Referece: https://prnt.sc/qvimev
<script>
require(["jquery"], function($) {
var url = $('.next').attr('href');
if (typeof url === "undefined") {
$('#load-more-product').html('');
}
$('#load-more-product-link').on('click', function() {
var url = $('.next').attr('href');
$('#load-more-product').hide();
$('#load-more-loader').show();
$.get(url, function(data) {
$('#load-more-loader').hide();
$('#load-more-product').show();
var result = $(data).find('.item.product.product-item');
var nxtUrl = $(data).find('.next').attr('href');
result.each(function(index, value) {
$('.products.list.items.product-items').append(value);
$("form[data-role='tocart-form']").catalogAddToCart();
});
if (typeof nxtUrl === "undefined") {
$('#load-more-product').html('<em>No More product in this Category.</em>');
} else {
$('.next').attr('href', nxtUrl);
}
});
});
});
</script>
Load More Infinite scroll is depends on Mageplaza Extension . so you need to make sure that Porto theme Mageplaza_LayeredNavigation Extension should be enabled

How to get rid of the loading progress in Facebook Instant Games with Phaser

I am developping a game for Facebook instant games with Phaser 2 CE, and i don't like the loading progress shown at the starting point, how can i get rid of it ?
I am using the default example given in the Quick Start page
FBInstant.initializeAsync()
.then(function() {
var images = ['phaser2'];
for (var i=0; i < images.length; i++) {
var assetName = images[i];
var progress = ((i+1)/images.length) * 100;
game.load.image('./assets/' + assetName + '.png');
// Informs the SDK of loading progress
FBInstant.setLoadingProgress(progress);
}
});
You can try something like given in this example like the code bellow then create your game, i know it's not clean but it works
FBInstant.initializeAsync()
.then(function() {
FBInstant.setLoadingProgress(50);
FBInstant.setLoadingProgress(100);
});
I have tryed something interesting but it doesn't answers the question according to this example
var sprite;
var PixelW = window.innerWidth;
var PixelH = window.innerHeight;
var game = new Phaser.Game(PixelW, PixelH, Phaser.AUTO, 'game', { preload: preload, create: create, update: update });
function preload() {
game.load.onLoadStart.add(loadStart, this);
game.load.onFileComplete.add(fileComplete, this);
startLoading();
}
function startLoading () {
game.load.image('logo1', 'assets/sprites/phaser1.png');
game.load.image('logo2', 'assets/sprites/phaser2.png');
game.load.image('dude', 'assets/sprites/phaser-dude.png');
game.load.image('ship', 'assets/sprites/phaser-ship.png');
game.load.image('mushroom', 'assets/sprites/mushroom.png');
game.load.image('mushroom2', 'assets/sprites/mushroom2.png');
game.load.image('diamond', 'assets/sprites/diamond.png');
game.load.image('bunny', 'assets/sprites/bunny.png');
game.load.start();
}
function create() {
game.stage.backgroundColor = 0x3b5998;
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
sprite = game.add.sprite(game.world.centerX, game.world.centerY, 'dude');
sprite.inputEnabled = true;
sprite.events.onInputDown.add(myHandler, this);
var text = game.add.text(10, 10, PixelW + " " + " " + PixelH, { font: "65px Arial", fill: "#ffff00", align: "center" });
}
function loadStart() {
}
// This callback is sent the following parameters:
function fileComplete(progress, cacheKey, success, totalLoaded, totalFiles) {
FBInstant.setLoadingProgress(progress);
//console.log(cacheKey + " " + progress);
}
function myHandler() {
sprite.anchor.setTo(0.5, 0.5);
sprite.x = Math.floor(Math.random() * PixelW);
sprite.y = Math.floor(Math.random() * PixelH);
}
function update() {
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="https://connect.facebook.net/en_US/fbinstant.6.0.js"></script>
<script src="phaser.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<script type="text/javascript">
var p = 0;
FBInstant.initializeAsync()
.then(function() {
//FBInstant.setLoadingProgress(50);
//FBInstant.setLoadingProgress(100);
});
// Once all assets are loaded, tells the SDK
// to end loading view and start the game
FBInstant.startGameAsync()
.then(function() {
// Retrieving context and player information can only be done
// once startGameAsync() resolves
var contextId = FBInstant.context.getID();
var contextType = FBInstant.context.getType();
var playerName = FBInstant.player.getName();
var playerPic = FBInstant.player.getPhoto();
var playerId = FBInstant.player.getID();
// Once startGameAsync() resolves it also means the loading view has
// been removed and the user can see the game viewport
// game.start();
});
</script>
<div id="game"></div>
<script src="game.js" type="text/javascript"></script>
</body>
</html>
I use the methods below, I increase the loading percent after each file is loaded with Phaser. Also I include a try catch so that when testing local game play the game does not crash.
preload: function () {
try{
FBInstant.initializeAsync()
.then(function() {
});
}
catch(err) {
console.log('FB Instant Games Error: No Internet Connected');
}
this.load.image('gameItem1', 'assets/sprite/game_item1.png');
this.load.image('gameItem2', 'assets/sprite/game_item2.png');
}
And then...
startFacebookGame: function(){
try{
FBInstant.startGameAsync()
.then(function() {
// Retrieving context and player information can only be done
// once startGameAsync() resolves
var contextId = FBInstant.context.getID();
var contextType = FBInstant.context.getType();
var playerName = FBInstant.player.getName();
var playerPic = FBInstant.player.getPhoto();
var playerId = FBInstant.player.getID();
// Once startGameAsync() resolves it also means the loading view has
// been removed and the user can see the game viewport
});
}
catch(err) {
console.log('Analytics Connection Error');
}
},
fileComplete: function(progress, cacheKey, success, totalLoaded, totalFiles) {
try{
FBInstant.setLoadingProgress(progress);
}
catch(err) {
console.log('FB Instant Games progress Failed: No Internet Connected.');
}
//console.log("Progress: " + progress);
},
Here's how I do it. You can build out from there.
function preload() {
// Load some assets
FBInstant.setLoadingProgress(100)
}
function create() {
FBInstant
.startGameAsync()
.then(() => {
// Here you can now get users name etc.
console.log(this)
})
}
FBInstant.initializeAsync()
.then(() => {
new Phaser.Game({
type: Phaser.AUTO,
width: window.innerWidth,
height: window.innerHeight,
scene: {
preload,
create
}
})
})

Use Protractor browser.driver as a variable

I'm using page object model and I'm stuck at how to put the browser.driver elements as a variable.
Here is an example of using it with Protractor's element:
var Messages = function() {};
var messagesLink = element(by.css('a[href*="/Messages"]'));
Messages.prototype.visitPage = function() {
messagesLink.click();
};
exports.Messages = new Messages();
Then I can use Messages.visitPage(); throughout my test. The problem is when I try to do the same thing with browser.driver:
var Login = function() {};
var usernameField = browser.driver.findElement(by.id('UserName'));
var passwordField = browser.driver.findElement(by.id('Password'));
var signOnButton = browser.driver.findElement(by.css('input[value="Sign On"]'));
var registeredUserName = 'user';
var registeredUserPass = 'pass';
Login.prototype.loginAsRegisteredUser = function() {
loginAs(registeredUserName, registeredUserPass);
};
var loginAs = function(userName, pass) {
usernameField.sendKeys(userName);
passwordField.sendKeys(pass);
signOnButton.click();
};
exports.Login = new Login();
The test instantly fails before even starting, throwing this error NoSuchElementError: Unable to locate element: *[id="UserName"]. The reason why I'm using browser.driver is because I'm accessing elements on a non-angular page. I want to try and keep angular and non-angular references separate from each other.
I'm not sure how Protractor handles this but in Selenium I can use the variable like so, static By cancelButton = By.id("cphMain_btnCancel");.
So, is there anyway that this can be done using Protractor?
Spec File:
var home = require('../../pages/home/Home.js').Home;
var headerHome = require('../../pages/home/HeaderHome.js').HeaderHome;
var login = require('../../pages/Login.js').Login;
describe('Registered User | DEV_Smoke |--- Home page: ', function() {
it('Navigates to the Home page', function() {
home.visitPage();
});
it('Prints the current URL (see build.log)', function() {
home.verifyHomeUrl();
});
it('Clicks Sign On link and signs in as a registered user', function() {
headerHome.clickSignOnLink();
login.loginAsRegisteredUser();
});
});
Easiest way would be to just wrap the findElement in functions and call them as needed
var Login = function() {};
var usernameField = function() {
return browser.driver.findElement(by.id('UserName')); //returns promise
}
var passwordField = function() {
return browser.driver.findElement(by.id('Password'));
}
var signOnButton = function() {
return browser.driver.findElement(by.css('input[value="Sign On"]'));
}
var registeredUserName = 'user';
var registeredUserPass = 'pass';
Login.prototype.loginAsRegisteredUser = function() {
loginAs(registeredUserName, registeredUserPass);
};
var loginAs = function(userName, pass) {
usernameField().sendKeys(userName);
passwordField().sendKeys(pass);
signOnButton().click();
};
exports.Login = new Login();
browser.driver is of type Webdriver and when calling findElement, selenium-webdriver will try to evaluate wherever it is stated in your code. So prior to your login method and possibly navigation to the login page, you are automatically looking for the WebElements for UserName, Password, and input[value="SignOn"].
In your code snippet, it looks like you should use element. When using element, at runtime, the findElement will be evaluated. This allows for more reusable code.
For non-angular pages, you might have to provide your own syncing or some arbitrary sleep. This usually occurs with animations, long load screens, etc.
Also make sure you return your promises so the jasmine wrapper evaluates your function properly.
var usernameField = element(by.id('UserName'));
var passwordField = element(by.id('Password'));
var signOnButton = element(by.css('input[value="Sign On"]'));
// make sure you return your promises so the jasmine wrapper
// evaluates your function properly.
var loginAs = function(userName, pass) {
return usernameField.sendKeys(userName).then(() => {
return passwordField.sendKeys(pass).then(() => {
return signOnButton.click();
});
});
};

Pass polymer form data to rest api

I'm looking for some way to pass data from a Polymer form fields to REST API,
actually, I'm using core-ajax to do it but I think is a bit heavy method to do it.
Are any standard way to do it?
This is my code:
<template>
<section>
<file-input class="blue" id="file" extensions='[ "xls" ]' maxFiles="1">{{ FileInputLabel }}</file-input>
</section>
<section>
<paper-button raised class="blue" disabled?="{{ (! Validated) || (Submitted) }}" on-tap="{{ Submit }}">
<core-icon icon="send"></core-icon>
Process
</paper-button>
</section>
<paper-toast id="toast" text=""></paper-toast>
<core-ajax id="ajax" url="/import-pdi" method="POST" handleAs="json" response="{{ response }}" on-core-complete="{{ SubmitFinished }}"></core-ajax>
</template>
<script>
Polymer("import-pdi-form", {
Validated: false,
Submitted: false,
FileInputLabel: "SELECT",
ready: function () {
this.shadowRoot.querySelector("#file").addEventListener("change", function(event) {
var container = document.querySelector("import-pdi-form");
container.Validated = (event.detail.valid.length != 0);
if (event.detail.valid.length == 0) {
container.shadowRoot.querySelector("#toast").text = "Invalid Format";
container.shadowRoot.querySelector("#toast").show();
container.FileInputLabel = "SELECCIONA L'ARXIU";
}
else {
container.FileInputLabel = event.detail.valid[0].name;
var form_data = new FormData();
form_data.append("file", event.detail.valid[0], event.detail.valid[0].name);
container.shadowRoot.querySelector("#ajax").body = form_data;
container.shadowRoot.querySelector("#ajax").contentType = null;
}
});
},
Submit: function() {
if ((this.Validated) && (! this.Submitted)) {
this.Submitted = true;
this.shadowRoot.querySelector("#ajax").go();
}
},
SubmitFinished: function(event, detail, sender) {
if (detail.xhr.status == 200) {
this.shadowRoot.querySelector("#toast").text = JSON.parse(detail.xhr.response).message;
}
else {
this.shadowRoot.querySelector("#toast").text = "Server Error";
}
this.shadowRoot.querySelector("#toast").show();
this.FileInputLabel = "SELECCIONA L'ARXIU";
this.shadowRoot.querySelector("#file").reset();
this.Submitted = false;
}
});
</script>
For submitting a form that contains custom elements we currently recommend that you use the ajax-form element. It looks like you may already be using the file-input element by the same author, so the two should work well together.

youtube iframe API does not work on ipad and iphone

I was trying to recreate the multiple iframes example detailed here for a slideshow. It works flawlessly in all browsers, including desktop safari, except on iphone and ipad.
http://codepen.io/lakshminp/pen/mepIB
Js:
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var players = {}
var YT_ready = (function() {
var onReady_funcs = [],
api_isReady = false;
return function(func, b_before) {
if (func === true) {
api_isReady = true;
for (var i = 0; i < onReady_funcs.length; i++) {
// Removes the first func from the array, and execute func
onReady_funcs.shift()();
}
}
else if (typeof func == "function") {
if (api_isReady) func();
else onReady_funcs[b_before ? "unshift" : "push"](func);
}
}
})();
function onYouTubeIframeAPIReady() {
jQuery(window).bind("load", function() {
YT_ready(true);
});
}
YT_ready(function() {
var identifier = "v9d09JLBVRc";
players[identifier] = new YT.Player(identifier, {
events: {
'onReady': onPlayerReady,
"onStateChange": createYTEvent(identifier)
}
});
});
function onPlayerReady(event) {
event.target.playVideo();
}
// Returns a function to enable multiple events
function createYTEvent(identifier) {
var player = players[identifier]; // Get cached player instance
return function (event) {
console.log(event.data);
}
}
HTML:
<div id="yt-container">
<iframe width="640" height="480" id="v9d09JLBVRc" class="media-youtube-player" src="//www.youtube.com/embed/v9d09JLBVRc?enablejsapi=1&autoplay=0" frameborder="0" allowfullscreen></iframe>
</div>
According to this
functions and parameters such as autoplay, playVideo(), loadVideoById() won't work in all mobile environments
and in your YTReady function, you load dynamically a video and for the moment that's not possible on iOS.
You can also try the YouTubeDemoPage and try to load another id and you will see that it can't be done.
You should also check this.