Onclick with 2 tasks - android

I'm trying to do 2 things at once with OnClick and don't know if I'm coding it wrong or if it's not possible. I'm trying to click on an image and using onclick go to another image while also playing a sound and then back to the original image. I have 3 examples in a row. The first example goes from image1 to image2 and back to image 1 without playing a sound. The 2nd example goes from image1 to image2 to image3 and back to image 1 without playing a sound. The third example plays a sound Onclick but its not going to image2. I want it to play a sound and also go to image2 when I click. Can anyone help?
http://readautism.atwebpages.com/index3.html
<!doctype html>
<html>
<head>
<meta charset="ISO-8859-1" />
<title>Example of How to Play a Sound on Click or on MouseOver</title>
<script>
var html5_audiotypes={ //define list of audio file extensions and their associated audio types. Add to it if your specified audio file isn't on this list:
"mp3": "audio/mpeg",
"mp4": "audio/mp4",
"ogg": "audio/ogg",
"wav": "audio/wav"
}
function createsoundbite(sound){
var html5audio=document.createElement('audio')
if (html5audio.canPlayType){ //check support for HTML5 audio
for (var i=0; i<arguments.length; i++){
var sourceel=document.createElement('source')
sourceel.setAttribute('src', arguments[i])
if (arguments[i].match(/\.(\w+)$/i))
sourceel.setAttribute('type', html5_audiotypes[RegExp.$1])
html5audio.appendChild(sourceel)
}
html5audio.load()
html5audio.playclip=function(){
html5audio.pause()
html5audio.currentTime=0
html5audio.play()
}
return html5audio
}
else{
return {playclip:function(){throw new Error("Your browser doesn't support HTML5 audio unfortunately")}}
}
}
//Initialize two sound clips with 1 fallback file each:
var mouseoversound=createsoundbite("whistle.ogg", "whistle.mp3")
var clicksound=createsoundbite('http://static.sfdict.com/staticrep/dictaudio/P05/P0501900.mp3', "whistle.ogg")
var uniquevar=createsoundbite("pizza.wav", "whistle.ogg", "whistle.mp3")
</script>
<script>
var gStorage = {};
function toogle(anImage, anAltSrcArr) {
if (typeof(anImage) === "undefined" || typeof(anAltSrcArr) === "undefined" || anAltSrcArr.length === 0) {
return;
}
var id = anImage.id;
var oldSrc = anImage.src;
if (typeof(gStorage[id]) === "undefined") {
gStorage[id] = {
'id': id,
'origSrc': oldSrc,
'i': 0
};
}
gStorage[id].i += 1;
if (gStorage[id].i > anAltSrcArr.length) {
gStorage[id].i = 0;
}
if (gStorage[id].i === 0) {
anImage.src = gStorage[id].origSrc;
} else {
anImage.src = anAltSrcArr[gStorage[id].i - 1];
}
}
</script>
</head>
<body
<p>Click on an image</p>
<img class="with-action" id="image1" name="image1" src="http://dummyimage.com/50/f00/fff&text=a" onclick='toogle(this, ["http://dummyimage.com/50/ab0/fff&text=b"]);' />
<img class="with-action" id="image2" name="image2" src="http://dummyimage.com/50/0f0/fff&text=a" onclick='toogle(this, ["http://dummyimage.com/50/0fa/fff&text=b", "http://dummyimage.com/50/0bb/fff&text=c"]);'/>
<img class="with-action" id="image3" name="image3" src="http://dummyimage.com/50/00f/fff&text=a" onclick="uniquevar.playclip()";'toogle(this, ["http://dummyimage.com/50/ab0/fff&text=b"])'; />
</body>
</html>

Try
<img class="with-action" id="image3" name="image3" src="http://dummyimage.com/50/0bb/fff&text=c" onclick="uniquevar.playclip();toogle(this, ['http://dummyimage.com/50/0fa/fff&text=b', 'http://dummyimage.com/50/0bb/fff&text=c']);">
Single and double quotes mix-up, apparent due to syntax-highlighting in the snippet that you posted.

Related

Set listener on WebView | nativescript + vue

I am trying to play a video from YouTube and get the current-time by YT.API.
The video plays successfully and functions on HTML content works too,
But I can't figure it out how can I get data from this webView Element.
I want to be informed about events from webView,
this is my code:
<template>
<Page #loaded=pageLoaded>
<GridLayout>
<web-view id="webView"></web-view>
</GridLayout>
</Page>
</template>
let webViewInterfaceModule = require('nativescript-webview-interface');
#Component
export default class someComponent extends Vue {
oWebViewInterface;
pageLoaded(args){
let page = args.object;
this.setupWebViewInterface(page);
}
setupWebViewInterface(page){
let webView = page.getViewById('webView');
this.oWebViewInterface = new webViewInterfaceModule.WebViewInterface(webView, this.html);
this.oWebViewInterface.on( '*', function(eventData){
console.log("some change!!"); // but never fires!
});
}
}
and i define this.html as:
html = `
<!DOCTYPE html>
<html>
<body>
<div id="player"></div>
<script>
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 player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '280',
width: '100%',
videoId: 'k3On6DLPGLA',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
console.log("state changed!"); // it fires!
}
function stopVideo() {
player.stopVideo();
}
<\/script>
<\/body>
<\/html>
`;
but i just get such these results:
chromium: [ERROR:web_contents_delegate.cc(224)] WebContentsDelegate::CheckMediaAccessPermission: Not supported.
chromium: [INFO:CONSOLE(35)] "state changed!", source: ..../ (35)
Ok I got the answer:
there is some issues here:
#1. implanting nativescript-webview-interface.js:
I need to copy this file:
cp node_modules/nativescript-webview-interface/www/nativescript-webview-interface.js app/assets/www/lib/
#2. permissions!
but #1 causes another problem: net::ERR_ACCESS_DENIED
for solving this one I add this:
setupWebViewInterface(page){
let webView = page.getViewById('webView');
webView.android.getSettings().setAllowFileAccess(true);
}
and now I have access to the folder so I moved this.html variable content to a new file : /assets/www/index.html
#3. setting src
since just now we have access to the folder, we need to (re)set the src of web-view so I add this one to the setupWebViewInterface Function:
this.oWebViewInterface = new webViewInterfaceModule.WebViewInterface( webView, '~/assets/www/index.html' );
note: I removed src from <webView /> since it causes problem! (if old and new src would be the same it will not reload!)
#4.defining Variables:
in html file I need to add this line:
var oWebViewInterface = window.nsWebViewInterface;
#5. defining listener:
I add this one: oWebViewInterface.emit('anyEvent', event);
inside this function:
function onPlayerStateChange(event) {
console.log("state changed!");
oWebViewInterface.emit('anyEvent', event);
}
Now it works :)

Using jQuery "swipe" function to navigate an array of images

I'm building a simple slideshow that is controlled by buttons when viewed on a computer and by swiping gestures on touch screen devices. This is a demo with 3 images.
Each image, its corresponding caption and the navigation are contained within one div. Here's the first one:
<div class="item" id="1">
<img src="...">
<div class="caption">
caption 1
</div>
<div class="navigation">
&lt 1 / 3 &gt
</div>
</div>
These divs are shown or hidden using the "click" and "swipeleft / swiperight" functions.
$(document).ready(function () {
$("#1prev").click(function () {
$("#1").hide();
$("#3").show();
});
$("#1").on("swipeleft", function () {
$("#1").hide();
$("#3").show();
});
$("#1next").click(function () {
$("#1").hide();
$("#2").show();
});
$("#1").on("swiperight", function () {
$("#1").hide();
$("#2").show();
});
});
The slideshow will contain as many as 40 images in total. Is there a way to condense the script? Is this a relatively efficient and accessible solution? Is the code written properly? Can it be improved?
You could do something like this:
For the items, I have assigned classes to the prev and next buttons instead of IDs.
<div class="item" id="1">
<img src="http://www.leecorbin.co/img1.jpg" width="50%" />
<div class="caption">caption 1</div>
<div class="navigation">
&lt
1 / 3
&gt
</div>
</div>
Then in script, on pagecreate
Hide all items and show only the first one.
Add a handler for swipeleft and swiperight on items.
Add a click handler for the navigation buttons
Within these handlers determine which direction we are going and which slide we are currently on.
Call a function passing in the direction and current slide; it determines the next slide to show and makes the transition.
$(document).on("pagecreate", "#page1", function () {
$(".item").hide().first(0).show();
$(document).on("swipeleft swiperight", ".item", function (e) {
var dir = 'prev';
if (e.type == 'swipeleft') {
dir = 'next';
}
GoToNextSlide($(this), dir);
});
$(document).on("click", ".navigation > a", function (e) {
var dir = 'prev';
if ($(this).hasClass("nextBtn")) {
dir = 'next';
}
var $item = $(this).closest(".item");
GoToNextSlide($item, dir);
});
});
function GoToNextSlide($item, direction) {
var $next;
if (direction == 'next') {
if ($item.next().length > 0) {
$next = $item.next();
} else {
$next = $(".item").first();
}
} else {
if ($item.prev().length > 0) {
$next = $item.prev();
} else {
$next = $(".item").last();
}
}
$item.fadeOut(function () {
$next.fadeIn();
});
}
Updated DEMO

Custom play button for YouTube player in Android (and other mobiles)?

It is easy to create a custom play button for an embed YouTube video using their API, however it seems that the button cannot launch the video in mobile environment, especially Android. When you click it there, screen simply goes forever black with ever spinning loading animation.
<div id="wrapper">
<div id="video">
</div>
Play
</div>
<script>
var player, tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('video', {
height: '320',
width: '240',
videoId: '5oxIQe3XngY',
playerVars: {
modestbranding: 1,
controls: 0,
rel: 0
}
});
player.addEventListener('onReady', function(e) {
document.getElementById('play').onclick = function() {
player.playVideo();
};
});
player.addEventListener('onStateChange', function(e) {
if (e.data == 1) {
document.getElementById('play').style.display = 'none';
}
});
};
</script>
Here's the fiddle: http://jsfiddle.net/HArsN/
Any solution to that? Is it necessary to launch the video through bundled button only?

How to access the specific camera on mobile phone through html5

When I use html5 'getUserMedia' API to access acamera on the android(4.0) phone, it comes out "front camera", but I want to open "back camera". Sample code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Html5 Mobile Carema</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(init);
function init() {
try {
window.URL = window.URL || window.webkitURL || window.msURL
|| window.oURL;
navigator.getUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia;
navigator.getUserMedia({
video : true
}, successsCallback, errorCallback);
} catch (err) {
// Tries it with old spec of string syntax
navigator.getUserMedia('video', successsCallback, errorCallback);
}
$(":button").click(function() {
slap();
});
}
function slap() {
var video = $("#myVideo")[0];
var canvas = capture(video);
$("#result").empty();
$("#result").append(canvas);
//alert();
var imgData = canvas.toDataURL('image/png;base64,');
//var imgData = canvas.toDataURL("image/png");
var imgData = imgData.substring(22);
//blb = dataURItoBlob(imgData);
//sendMsg(blb);
}
function errorCallback(err) {
}
function successsCallback(stream) {
$("#myVideo").attr("src", window.webkitURL.createObjectURL(stream));
}
function capture(video) {
var canvas = document.createElement('canvas');
var width = video.videoWidth;
var height = video.videoHeight;
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
var context = canvas.getContext('2d');
context.drawImage(video, 0, 0, 160, 120);
return canvas;
}
</script>
</head>
<body>
<video id="myVideo" autoplay="autoplay"></video>
<br> <input type="button" value="capture" />
<br><div id="result" style="width: 145px"></div>
<div>
<p id="resultMsg" style="color: red"></p>
<p id="decodeTime" style="color: green"></p>
</div>
</body>
</html>
I don't know how to access specific camera on android phone, anyone who knows? thanks
There is now the ability to specify a camera in the latest specification with the facingMode property: http://www.w3.org/TR/mediacapture-streams/#idl-def-VideoFacingModeEnum
This property is an optional part of the MediaStreamConstraints object that is the first argument of the getUserMedia method.
Here's a simplified example from the spec:
var supports = navigator.mediaDevices.getSupportedConstraints();
if (!supports["facingMode"]) {
// Handle lack of browser support if necessary
}
var gotten = navigator.mediaDevices.getUserMedia({
video: {
facingMode: {exact: "environment"}
}
});
The value environment means the back camera of the device. Other values are user, left and right.
Note that support for this varies depending on the browser/browser version.
See function gotSources(sourceInfos) in the code below
<!--
Based on Motion Detector Demo Created by Ákos Nikházy.
If you use this app please link this demo http://motion-detector.nikhazy-dizajn.hu/
-->
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Frame capture demo</title>
</head>
<body>
<header>
<h1>Motion Detection</h1>
<h4>with HTML5 API using .getUserMedia()</h4>
</header>
<video autoplay></video>
<hr>
<canvas id="savePhoto"></canvas>
<script>
function hasGetUserMedia() {
//returns true if supported
return !!(navigator.getUserMedia || navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia);
}
function onSuccess(stream) {
//If we can stream from camera.
var source;
//Get the stream. This goes to the video tag
if (window.URL) {
source = window.URL.createObjectURL(stream);
} else if (window.webkitURL) {
source = window.webkitURL.createObjectURL(stream);
} else {
source = stream; // Opera and Firefox
}
//Set up video tag
video.autoplay = true;
video.src = source;
//We try to find motion in every X second
setInterval(function() {
motionDetector();
}, sampling);
}
function onError() {
//if we fail (not supported, no camera etc.)
alert('No stream, no win. Refresh.');
}
function saveImage(canvasToSave) {
//create image from canvas
dataUrl = canvasToSave.toDataURL();
imageFound = document.createElement('img');
imageFound.src = dataUrl;
document.body.appendChild(imageFound);
}
function motionDetector() {
ctxSave.drawImage(video, 0, 0, savePhoto.width, savePhoto.height);
}
/*After all those functions lets start setting up the program*/
//Set up elements. Should be a ini() but I don't care right now
var video = document.querySelector('video'); //the video tag
var savePhoto = document.getElementById('savePhoto'); //the possible saved image's canvas
var ctxSave = savePhoto.getContext('2d'); //the latest image from video in full size and color
var sampling = 1000; //how much time needed between samples in milliseconds
var videoSourceInfo = null;
//We need this so we can use the videoWidth and ...Height, also we setup canvas sizes here, after we have video data
video.addEventListener("loadedmetadata", function() {
console.log(video.videoWidth + ":" + video.videoHeight)
savePhoto.width = video.videoWidth;
savePhoto.height = video.videoHeight;
});
function start() { //Start the whole magic
if (hasGetUserMedia()) {
//it is working?
navigator.getUserMedia
|| (navigator.getUserMedia = navigator.mozGetUserMedia
|| navigator.webkitGetUserMedia
|| navigator.msGetUserMedia);
var videoSourceInfoId = videoSourceInfo.id;
var constraints = {
video : {
optional: [{sourceId: videoSourceInfoId}]
},
toString : function() {
return "video";
}
};
navigator.getUserMedia(constraints, onSuccess, onError);
} else {
//no support
alert('getUserMedia() is not supported in your browser. Try Chrome.');
}
}
function gotSources(sourceInfos) {
for (var i = sourceInfos.length-1 ; i >= 0; i--) { // get last camera index (supposed to back camera)
var sourceInfo = sourceInfos[i];
if (sourceInfo.kind === 'video') {
videoSourceInfo = sourceInfo;
console.log('SourceId: ', videoSourceInfo.id);
start();
break;
} else {
console.log('Some other kind of source: ', sourceInfo);
}
}
}
if (typeof MediaStreamTrack === 'undefined') {
alert('This browser does not support MediaStreamTrack.\n\nTry Chrome Canary.');
} else {
MediaStreamTrack.getSources(gotSources); // async task
}
</script>
</body>
</html>
Hi I think this works with you
<script>
var gum = mode =>
navigator.mediaDevices.getUserMedia({video: {facingMode: {exact: mode}}})
.then(stream => (video.srcObject = stream))
.catch(e => log(e));
var stop = () => video.srcObject && video.srcObject.getTracks().forEach(t => t.stop());
var log = msg => div.innerHTML += msg + "<br>";
</script>
<button onclick="stop();gum('user')">Front</button>
<button onclick="stop();gum('environment')">Back</button>
<div id="div"></div><br>
<video id="video" height="320" autoplay></video>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
facingMode??
https://github.com/webrtcHacks/adapter/issues/820
https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/facingMode

Make absolute positioned span/div scrollable on android - more than one span/div

I need help with a little problem I can't seem to get a grip to:
I have spans that show up on the bottom of the screen when I touch a character (a lot of characters -> a lot of spans). In the span are some information about the character - as I want to make it mobilefriendly I want the user to scroll throught that information.
So far I found a little bit code that helped me a little:
<body onload="touchScroll('test')">
<script>
function isTouchDevice(){
try{
document.createEvent("TouchEvent");
return true;
}catch(e){
return false;
}
}
function touchScroll(id){
if(isTouchDevice()){ //if touch events exist...
var el=document.getElementById(id);
var scrollStartPos=0;
document.getElementById(id).addEventListener("touchstart", function(event) {
scrollStartPos=this.scrollTop+event.touches[0].pageY;
event.preventDefault();
},false);
document.getElementById(id).addEventListener("touchmove", function(event) {
this.scrollTop=scrollStartPos-event.touches[0].pageY;
event.preventDefault();
},false);
}
}
And the span with the id "test" becomes scrollable. Great. But as I have hundreds of span I can't assign an id to every single one. So I was wondering if you could help come up with a way to make every class "tt" scrollable.
I tried reassigning the "test"-id to the next element upon touch. But that didn't work. I tried adding the "test"-id to every class "tt" - didn't work either.
If you want to make yourself a picture of the situation: Here's my testsite!
I found a solution on this site in the comments:
<script type='text/javascript'>
// Determine if this is a touch device
var hasTouch = 'ontouchstart' in document.documentElement,
startEvent = hasTouch ? 'touchstart' : 'mouseover',
moveEvent = hasTouch ? 'touchmove' : 'mousemove',
endEvent = hasTouch ? 'touchend' : 'mouseup';
var Last;
$(".tttw").live(startEvent, function() {
if (Last) Last.removeClass('ttth');
$(this).addClass("ttth");
Last=$(this);
});
function isTouchDevice(){
try{
document.createEvent("TouchEvent");
return true;
}catch(e){
return false;
}
}
function touchScroll(selector) {
if (isTouchDevice()) {
var scrollStartPosY=0;
var scrollStartPosX=0;
$('body').delegate(selector, 'touchstart', function(e) {
scrollStartPosY=this.scrollTop+e.originalEvent.touches[0].pageY;
scrollStartPosX=this.scrollLeft+e.originalEvent.touches[0].pageX;
});
$('body').delegate(selector, 'touchmove', function(e) {
if ((this.scrollTop < this.scrollHeight-this.offsetHeight &&
this.scrollTop+e.originalEvent.touches[0].pageY < scrollStartPosY-5) ||
(this.scrollTop != 0 && this.scrollTop+e.originalEvent.touches[0].pageY > scrollStartPosY+5))
e.preventDefault();
if ((this.scrollLeft < this.scrollWidth-this.offsetWidth &&
this.scrollLeft+e.originalEvent.touches[0].pageX < scrollStartPosX-5) ||
(this.scrollLeft != 0 && this.scrollLeft+e.originalEvent.touches[0].pageX > scrollStartPosX+5))
e.preventDefault();
this.scrollTop=scrollStartPosY-e.originalEvent.touches[0].pageY;
this.scrollLeft=scrollStartPosX-e.originalEvent.touches[0].pageX;
});
}
}
$(document).ready(function(){
touchScroll('.tt');
});
</script>
Working like a charm now ;-)

Categories

Resources