Tuesday, June 11, 2019

Proper way to reference files

When referring to stylesheets or js files from index.html,

Do not put /src/app.js

Correct way is   src/app.js

Saturday, May 4, 2019

Overriding css styles

In order to override certain css styles from onsen or jquery mobile, or, possibly even bootstrap, you can put !important at the end of the style, eg.

h3 {
margin-left: 20px !important;
}

Thursday, April 18, 2019

JQuery: How to create element and set event listener at same time

Example:

var cell = $('<div>').on('click', function() {
$('#navigator')[0].bringPageTop('gallery.html', {
data: { pokenumber, savedPokemon }
});
})[0];


Creates a div and adds click event listener.

Reference:

CSS: What are viewport units vw

An example:

#grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-auto-rows: 33vw;
}

Reference:

Viewport Width (vw) – A percentage of the full viewport width. 10vw will resolve to 10% of the current viewport width, or 48px on a phone that is 480px wide. The difference between % and vw is most similar to the difference between em and rem. A % length is relative to local context (containing element) width, while a vw length is relative to the full width of the browser window.

https://css-tricks.com/fun-viewport-units/


Wednesday, April 17, 2019

CSS: How to specify a child div

Example:

.grid-container > div {
  background-color: rgba(255, 128, 255, 0.8);
  text-align: center;
  padding: 20px 0;
  font-size: 30px;
}

References:

https://www.w3schools.com/cssref/tryit.asp?filename=trycss_grid-template-columns2


Jquery: how to create an element and set attribute at the same time

Example:

var image = $('<img>', { src: `img/${pokenumber}.png` })[0];


or

var image = $('<img>').attr('src', `img/${pokenumber}.png`)[0];

Reference:

https://stackoverflow.com/questions/22886101/jquery-create-a-new-element-with-data-html-attribute



JQuery and Javascript equivalents

Good list of equivalent:

https://gist.github.com/joyrexus/7307312


Free bootstrap builder?

Is it really free:

https://mobirise.com/_l/bootstrap-website-builder/?gclid=EAIaIQobChMIxLW8mp_X4QIVFfOPCh3FbgvvEAEYASAAEgLUlfD_BwE


jquery: What is the meaning of $.

For example, $.something.

See:

https://forums.asp.net/t/1712958.aspx?JQuery+meaning


Tuesday, April 16, 2019

Node.js: getting input from command line

npm i readline-sync --save

Then:

const read = require('readline-sync');

var inputstr = read.question('enter name: ');

console.log('hello ' + inputstr);

Reference:
https://teamtreehouse.com/community/how-to-get-input-in-the-console-in-nodejs

Onsen: how to listen for events

An example:

https://github.com/paulchin/onsen-06-tutorial/blob/master/www/app.js

Reference:

https://onsen.io/v2/guide/tutorial.html#events


jquery selector parent descendant

How to select child of a parent?

$('#home-toolbar .center').html(tabItem.getAttribute('label'));


Selects the center class of home-toolbar

From:

https://github.com/paulchin/onsen-06-tutorial/blob/master/www/app.js

Reference:

https://www.w3schools.com/jquERY/sel_parent_descendant.asp


Onsen: list of available icons

Onsen does not publish a list of available icons instead sends you to this page:

https://material.io/tools/icons/?icon=delete_outline&style=baseline

But not every icon on that page is available in the default Onsen download.
To see what's available look in this file:


Update:

You can see a list of icons here:

Just append md-  in front.

It is accessed from here:

The 3rd link:  'Material Design Iconic Font'.

Then, in the zavoloklom page, click on Icons link on top.


Onsen: how to center toolbar text

Use the style:

text-align: center in the div


Here is an example:

<ons-toolbar id="home-toolbar">
<div class="center" style="text-align: center">Home</div>
</ons-toolbar>

You don't need to do that for iOS. But if you want to center it for both iOs and Android then use it.

Material design


https://www.youtube.com/watch?v=tfSiXRy1vEw

https://material.io/

https://www.polymer-project.org/


Sunday, April 14, 2019

Onsen ons object

Difference between document init and ons.ready:

https://onsen.io/v2/guide/fundamentals.html#the-ons-object

The ons JavaScript object is globally available, and has several useful methods and properties.
For example, ons.ready(callback) method can be used to wait for app initialization. Specifically, this function waits until “DOMContentLoaded” and Cordova’s “deviceready” events are fired. This is useful, for instance, to know when is safe to make calls to Cordova APIs.

Loading external html files with Onsen

Using Onsen navigator.

Create a separate page called page2.html:

<ons-page id="page2">
<ons-toolbar>
<div class="left"><ons-back-button>Page 1</ons-back-button></div>
<div class="center">Page 2</div>
</ons-toolbar>

<p>This is the second page.</p>
</ons-page>

Then load it as follows:

$(document).on('init', function(event) {
//ons.notification.alert('Button is tapped!');
var page = event.target;
if (page.id === 'page1') {
$('#push-button').on('click', function() {
$('#myNavigator')[0].pushPage('page2.html', {
data: { title: 'Page 2' }
});
});
}
});

The index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"
/>
<title>Blank App</title>
<link rel="stylesheet" href="css/onsenui.css" />
<link rel="stylesheet" href="css/onsen-css-components.min.css" />
</head>
<body>
<ons-navigator swipeable id="myNavigator" page="page1.html"></ons-navigator>

<template id="page1.html">
<ons-page id="page1">
<ons-toolbar>
<div class="center">Page 1</div>
</ons-toolbar>

<p>This is the first page.</p>

<ons-button id="push-button" onclick="pushPage()">Push page</ons-button>
</ons-page>
</template>

<script type="text/javascript" src="cordova.js"></script>
<script src="js/onsenui.min.js"></script>
<script src="js/jquery-3.4.0.min.js"></script>
<script src="app.js"></script>
</body>
</html>

That's it. Note that <ons-template> is only necessary inside index.html, not in a separated file.

Onsen pushPage with jquery

How to pushPush with Onsen using jquery:

function pushPage() {
$('#myNavigator')[0].pushPage('page2.html', { data: { title: 'Page 2' } });
}

Wednesday, April 10, 2019

Saturday, April 6, 2019

JQuery Gaming

Nice resource:

http://www.bestjquery.com/example/games/


JQuery Mobile Game Programming

Nice slides:

https://www.slideshare.net/rockncoder/beginning-html5-mobile-game-programming-with-jquery-mobile


JQuery Mobile UI Builder

Chrome extension:

https://chrome.google.com/webstore/detail/appmint-lite-html5jquery/imdkdmbnblpapcdidcofglgbjbgaegle?hl=en

Sadly, broken. Widgets icons on bottom right won't show.

Other related UI builders:

https://chrome.google.com/webstore/detail/appmint-lite-html5jquery/imdkdmbnblpapcdidcofglgbjbgaegle/related?hl=en


2 ways to load external html file

First way:

function load1Content() {
$('.ui-content').load('1.html');
$('[data-role=listview]').listview(); // premature execution
window.scrollTo(0, 0);
}

Second way:

function loadHomeContent() {
$.ajax('home.html')
.done(function(home) {
$('.ui-content').html(home);
$('[data-role=listview]').listview();
})
.fail(function() {
console.log('ajax home content error');
});

window.scrollTo(0, 0);
$('#top-title').html('PhoneGap AdMob');
}


Which way to use?

First way is shorter and simpler but it won't format the markup if there are ul or li. That is because premature execution of listview() happens even before the html is loaded. The .load() is asynchronous.

Therefore, the second way is the correct way if your html has ul, li or other markup which needs to be formatted. It ensures that .listview() is executed ONLY AFTER the html has loaded.

To prevent truncated text ...

To prevent text from being truncated and replaced with ...
do this in the css:

p {
white-space: normal !important;
}

That's it!

How to crop images using css

In style:

<style>
#test {
width: 100%;
margin: -30% 0;
}
</style>


About -30% means crop 30% vertically.

In body:



<img src="images/pic1.jpg" id="test"/>

That's it!

Wednesday, April 3, 2019

How to force refresh

Add this in the markup

<div data-role="collapsibleset" data-ajax="false">

It will refresh the content. Note data-ajax = false


Tuesday, April 2, 2019

How to return something from ajax

Use a callback:

function something(callback){
 $.ajax({
        'url':'/some/url',
        'type':'GET',
        'data':{'some':'data'},
        'success': callback
   });
}

something(function (data) {
    data['id']; // use it here
})


See:

https://stackoverflow.com/questions/8187201/return-value-from-inside-of-ajax-function


Saturday, March 30, 2019

How to fit all images within content and yet maintain aspect ratio

Use this css:

img{
 min-width: 100%;
 height: auto;
}

How to debug apk using Chrome

Use type this in the url :

chrome://inspect/#devices

It will debug all devices including emulators eg, nox player and also physical devices connected via usb:


Tuesday, March 26, 2019

Getting Started with Framework 7

git clone Framework 7's kitchen sink:

https://github.com/framework7io/framework7/

Open the kitchen sink index.html inside visual studio code and run Live Server




Wednesday, March 6, 2019

Tuesday, March 5, 2019

Ajax: Simplest json call

The simplest of all:

var url = 'http://test.com/php/getnews.php';

  $.getJSON(url, function(result) {
    console.log(result);
    $.each(result, function(i, field) {
      console.log(i + ':' + field.title);
    });
  });

and the corresponding php on the server:

$query = "SELECT * FROM news";
  $rows = array();

  if($result = mysqli_query($link, $query)) {
      while($r = mysqli_fetch_assoc($result)) {
        $rows[] = $r;
      }
   
      header('Content-Type: application/json');
      print json_encode($rows,
      JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_HEX_TAG | JSON_FORCE_OBJECT );
   
  }

Monday, March 4, 2019

Ajax with Cross Domain


Another ajax example:


var url = 'http://test.com/php/getnews.php';


$.ajax({
   type: 'GET',
   url: url,
   crossDomain: true,
   cache: false,
   success: function(result) {

        / / var obj = $.parseJSON(result[0]);
        console.log(result);
 
         $.each(result, function(i, field) {
              console.log(i + ':' + field.title);
         });
     }
});

Ajax Simple Example



$.ajax(
  'https://api.wmata.com/Rail.svc/json/jStations?LineCode=BL&api_key=' + key
)
.done(function(data) {
     console.log(data);
     var stationList = new Array();
     console.log('Length: ' + data.Stations.length);
     for (var x = 0; x < data.Stations.length; x++) {
     console.log(x);
     var name = data.Stations[x].Name;
     var id = data.Stations[x].Code;
     var thisStation = new Station(name, id);
    stationList.push(thisStation);
}

for (var x = 0; x < stationList.length; x++) {
   var out = "<option value='" + stationList[x].stationId + "'>";
   out += stationList[x].stationName;
   out += '</option>';
   document.getElementById('stationListSelector').innerHTML += out;
}
})
.fail(function() {
   alert('error');
});

Ajax Complete Example: Full Headers


$.ajax({
    url: 'https://api.wmata.com/Rail.svc/json/jStations?' + $.param(params), //LineCode=BL
    beforeSend: function(xhrObj) {
      //Request headers
      xhrObj.setRequestHeader('api_key', key);
    },
    type: 'GET',
    // Request body
    data: '{body}'
  })
    .done(function(data) {
      console.log(data);
      var stationList = new Array();
      console.log('Length: ' + data.Stations.length);
      for (var x = 0; x < data.Stations.length; x++) {
        console.log(x);
        var name = data.Stations[x].Name;
        var id = data.Stations[x].Code;
        var thisStation = new Station(name, id);
        stationList.push(thisStation);
      }
      for (var x = 0; x < stationList.length; x++) {
        var out = "<option value='" + stationList[x].stationId + "'>";
        out += stationList[x].stationName;
        out += '</option>';
        document.getElementById('stationListSelector').innerHTML += out;
      }
    })
    .fail(function() {
      alert('error');
    });

Ajax Basic Template


$.ajax('http://www.somewebsite.com')
.done(function(){})
.fail(function(){});

Ajax: Search Pokemon


https://github.com/paulchin/hc-webdev-notes/blob/master/4-jquery/searchpokemon.html

Fetching Blobs from MySQL

Here is the php script to fetch blob from MySQL database:


<?php

  header('Access-Control-Allow-Origin: *');

  $link = mysqli_connect("host","username","passwd", "database");

  mysqli_set_charset($link, "utf8");

  if(mysqli_connect_error()) {
    die("There was an error");
  }

  $query = "SELECT pic FROM news WHERE id=1";

  $rows = array();

  if($result = mysqli_query($link, $query)) {
      while($r = mysqli_fetch_assoc($result)) {
        $rows[] = $r;
      }
      echo '<img src="data:image/jpeg;base64,'.base64_encode( $rows[0]['pic'] ).'"/>';
  }

?>

Saturday, March 2, 2019

Proper window size and layout size for Construct 2 Mobile Games

When creating a new mobile game, make sure to select:


That is, the windows size is 16:9  aspect ratio, i.e. windows size: 480 x 854 either landscape or portrait:


Also, be sure to set the Fullscreen in browser to:  Scale inner.
After building the apk files, testing on Samsung Galaxy Tab4 tablet and Redmi Note2, below is the result:



Wednesday, February 27, 2019

How to create your own Web API using PHP and access it using a PhoneGap app

In this tutorial, we will create a simple end-to-end system consisting of MySQL database and also a php script to access the database with some simple API. Then, we will create a simple PhoneGap app to access the Database via the API.

Start HTTP web server and MySQL server of your xamp app. Then using phpmyadmin create a table consisting of:


Also, populate the table with some data as shown above.

In the xamp folder's htdocs folder, create a subfolder mysql and create a new file called jsonencode.php :

<?php
// This one is working
// The client is Phonegap app: PHP API Client
header('Access-Control-Allow-Origin: *');
$link = mysqli_connect("localhost","myuser","mypassword", "paul");
if(mysqli_connect_error()) {
die("There was an error");
}

//$query = "SELECT * FROM users";
$query = "SELECT * FROM users WHERE name = '".$_GET['name']."'";

$rows = array();

if($result = mysqli_query($link, $query)) {
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode($rows);
}

?>

Create a client PhoneGap app called PHP API Client containing 2 files: index.html and app.js.

index.html :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"
/>
<title>Blank App</title>
<link
rel="stylesheet"
href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"
/>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header" data-position="fixed">
<h1>PHP Client</h1>
<div class="searchform" style="padding:6px">
<label for="text-basic">Enter Name:</label>
<input
type="search"
name="text-basic"
id="txtinputname"
value=""
placeholder="Enter Name"
/>
<input
type="button"
value="Search"
data-icon="search"
id="btnsearch"
/>
</div>
</div>
<div role="main" class="ui-content centered">
<div id="result">Search Results...</div>
<br />
<div id="list">
<ul data-role="listview" id="resultlist"></ul>
</div>
</div>
<div data-role="footer" data-position="fixed">
<h2>by PHP API Client Crew</h2>
</div>
</div>

<!-- <script type="text/javascript" src="cordova.js"></script> -->
<script type="text/javascript" src="app.js"></script>
</body>
</html>

app.js:

$('#btnsearch').click(function() {
var name = $('#txtinputname')
.val()
.toLowerCase();
console.log(name);
var url = 'http://192.168.137.84/mysql/jsonencode.php?name=' + name;
console.log(url);
//clear the listview
$('#list').html("<ul data-role='listview' id='resultlist'></ul>");

$.ajax(url)
.done(function(data) {
var obj = JSON.parse(data);
console.log(data);
//console.log(obj[0].name);
var output = '';
if (obj[0]) {
obj.forEach(function(record) {
console.log(record.name);
output +=
'<li>id: ' +
record.id +
' Name: ' +
record.name +
' email: ' +
record.email +
'</li>';
});
} else {
output += '<li>Not Found</li>';
}

$('#resultlist').append(output);
$('#resultlist')
.listview()
.listview('refresh');
})
.fail(function() {
$('#result').html(name + ' not found!');
});
});

The index.html will refer to the app.js

Then Run the PhoneGap app using PhoneGap Desktop App and connect to it with a Browser and try to access some record by keying in  a name: