If condition not working with device orientation - javascript

So guys, I am playing with device orientation.
Here is it https://sublime.glitch.me/
Everything went well except the if condition.
If you could please look at the webpage on mobile device, you will see the png moves according to the device orientation.
But I dont want it to go off the screen, this is where I need if condition. I tried to make the evt.gamma not greater than 35 or smaller than -35 with if condition.
But apparently, what I have is not working. Sorry for my poor coding knowledge, I am a designer not a developer, can someone please help me not?
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-52746336-1');ga('send','pageview');
var isCompleted = {};
function sampleCompleted(sampleName){
if (ga && !isCompleted.hasOwnProperty(sampleName)) {
ga('send', 'event', 'WebCentralSample', sampleName, 'completed');
isCompleted[sampleName] = true;
}
}
var fixed = 2;
var h5logo = document.getElementById("h5logo");
var timestamp = document.getElementById("timestamp");
var alpha = document.getElementById("alpha");
var beta = document.getElementById("beta");
var gamma = document.getElementById("gamma");
/* // [START devori] */
if (window.DeviceOrientationEvent) {
window.addEventListener('deviceorientation', deviceOrientationHandler, false);
document.getElementById("doeSupported").innerText = "";
}
/* // [END devori] */
var deviceOrientationData;
function deviceOrientationHandler(evt) {
deviceOrientationData = evt;
try {
timestamp.innerText = new Date(evt.timeStamp);
alpha.innerText = evt.alpha.toFixed(fixed);
beta.innerText = evt.beta.toFixed(fixed);
gamma.innerText = evt.gamma.toFixed(fixed);
if(evt.gamma<-35){evt.gamma=-35}
if(evt.gamma>35){evt.gamma=35}
var trans = " translate("+ ((evt.gamma+20) * 2)+"px, "+ ((evt.beta-90) * -3)+"px) " ;
h5logo.style.webkitTransform = trans;
h5logo.style.transform = trans;
} catch (ex) {
document.getElementById("doeSupported").innerText = "NOT";
}
}
.h5logo {
width: 40vh;
display: block;
margin-left: auto;
margin-right: auto;
position:absolute;
z=index:10;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
<script defer src="https://code.getmdl.io/1.2.1/material.min.js"> .
</script>
<style>
body {
margin: 2em;
}
</style>
<title>👌</title>
</head>
<body>
<div role="main" class="container">
<img src="https://cdn.glitch.com/8da575e7-c6aa-48cb-bb49-3a708f8c28fc%2Fpreview.png?1535142774062" style="display: block; position: absolute; margin-left:auto; margin-right:auto; z-index:-2">
<img id="h5logo" src="https://cdn.glitch.com/8da575e7-c6aa-48cb-bb49-3a708f8c28fc%2Fhand.png?1535129311138" class="h5logo">
<h1 style="position:absolute; z-index:-1; transform: rotate(90deg) translate(20%,-60%);">
sublime
</h1>
<p>
<b>alpha:</b> <span id="alpha"></span><br>
<b>beta:</b> <span id="beta"></span><br>
<b>gamma:</b> <span id="gamma"></span><br>
</p>
<p>
<span id="timestamp" ></span>
</p>
</div>
</body>
</html>
The lines not working are here, the translation works fine, just the if condition. Thanks so much guys.
if(evt.gamma<-35){evt.gamma=-35}
if(evt.gamma>35){evt.gamma=35}
var trans = " translate("+ ((evt.gamma+20) * 2)+"px, "+
((evt.beta-90) * -3)+"px) " ;

All event properties, including gamma are read-only, so you need to assign -35 and 35 to a new variable. See the documentation.
Example:
let newGamma = evt.gamma;
if(evt.gamma < -35){
newGamma = -35;
}
else if(evt.gamma > 35){
newGamma = 35;
}
var trans = " translate(" + ((newGamma + 20) * 2) + "px, " + ((evt.beta - 90) * -3) + "px) ";
Simpler example, using Math methods:
var trans = " translate(" + ((Math.min(Math.max(evt.gamma, -35), 35) + 20) * 2) + "px, " + ((evt.beta - 90) * -3) + "px) ";

Related

Curved text with pure JS or React.js

I want to create a curved text that will change its curvature based on the value from the input range. If the value of the input is positive, then the curvature of the text should be downwards, if the value is negative, then the curvature should be upwards, and if it is 0, then the text will not have curvature.
The written code must be without any library, canvas, svg path object. Must be pure javascript or React.js
I want to get like this result
https://www.youtube.com/watch?v=RU63sdgydPE
This code is not working properly․
HTML
const updateCurvedText = (curvedText, radius) => {
const diameter = 2 * radius
const w = curvedText.offsetWidth
const h = curvedText.offsetHeight
const L = Math.PI * radius
const text = curvedText.innerText
let html = ""
textArr = text.split("")
textArr.forEach((item) => {
html += "<span>" + item + "</span>"
})
curvedText.innerHTML = html
let letters = curvedText.querySelectorAll("span")
if (!letters) {
return
} else {
letters.forEach((letter, index) => {
const angleRad = w / (2 * radius * Math.PI)
const angle = (360 * angleRad) / (letters.length * Math.PI)
const deltaDegree = L / letters.length
let deg = index * angle - (letters.length * angle) / 2
letter.style.height = `${radius}px`
letter.style.transform = `translate( ${w / 2}px, 0px) rotate( ${deg}deg)`
curvedText.style.height = `${radius}px`
deg += deltaDegree
})
}
}
const curvedText = document.querySelector(".curved-text")
updateCurvedText(curvedText, 2000)
const settingsChanged = (value) => {
curvedText.innerText = document.querySelector(".text").value
updateCurvedText(curvedText, value)
}
const showValue = (value) => {
settingsChanged(value)
}
document.querySelector(".text").onchange = () => {
const value = document.querySelector(".radius").value
settingsChanged(value)
}
.curved-text {
display: flex;
justify-content: space-between;
border-radius: 100%;
position: relative;
box-shadow: 0 0 30px rgba(0, 0, 0, 0.2);
}
.curved-text span {
color: blue;
width: 0;
outline: 1px dashed gray;
position: absolute;
transform-origin:bottom center ;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./style.css" />
<title>Document</title>
</head>
<body>
<div>
<fieldset>
<label>Text:</label>
<input type="text" class="text" value="CURVED TEXT TEST" />
<label>Radius:</label>
<input
class="radius"
type="range"
step="10"
min="100"
max="2000"
value = "2000"
oninput="showValue(this.value)"
onchange="showValue(this.value)"
/>
</fieldset>
</div>
<div class="curved-text">CURVED TEXT TEST</div>
<script src="./js/new.js"></script>
</body>
</html>

dynamic change in javascript, won't move my div

Hi there fellow programmers!
I Want to be able to type in to the boxes how much px i want my div to move. But it won't move and I cant see whats wrong with my code. Can someone with fresh eyes spot the problem?
Any help is much appreciated!
Here's the code so far:
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title> javascript</title>
<style>
#changeme {
background-color: lightblue;
position: absolute;
}
</style>
<script>
var $Rob = {};
$Rob.moveUpp = 0;
$Rob.moveLeft = 0;
$Rob.elementid = "";
$Rob.move = function(elementid, movex, movey)
{
$Rob.moveUpp = movey;
$Rob.moveLeft = movex;
$Rob.elementid = elementid;
$Rob.movesoft();
}
$Rob.movesoft = function() {
var elem = document.getElementById($Rob.elementid);
if ($Rob.moveUpp > 0) {
elem.style.top = (parseInt(elem.style.top) + 1) +
"px";
$Rob.moveUpp--;
} else if ($Rob.moveUpp < 0) {
elem.style.top = (parseInt(elem.style.top) - 1) +
"px";
$Rob.moveUpp++;
}
if ($Rob.moveUpp != 0) {
setTimeout($Rob.movesoft, 100);
}
}
</script>
</head>
<body>
<h1> Dynamic changes </h1>
<form>
<p>Move right:</p> <input value="0" type="text" id="moveRight" />
<p>Move down: </p> <input value="0" type="text" id="moveDown" />
<input type="button" value="Move" onClick="$Rob.move(document.getElementById('changeme'),parseInt(document.getElementById('moveRight').value),parseInt(document.getElementById('moveDown').value));" />
</form>
<div id="changeme" style="top: 100px;left: 100px;"> Hello </div>
</body>
</html>
All the best
I love Stackoverflow and its members!
cheers
// Mcgayjver
You're doing:
$Rob.move(document.getElementById('changeme'), x, y).
When you should just be doing:
$Rob.move('changeme, x, y)
Because $Rob.move expects an elementID string as a first parameter, not an actual HTMLElement.

How can I make dynamic progress bar using just jquery?

I wrote a code for progressbar using jquery it works as expect but if I add second element all element works same that is why I guess I have to make it dynamic but I have no idea to do how can I make it as dynamic ?
HTML
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<div class="trustyou-progressbar pull-right">
<p class="trustyou-puan">100/72 Puan</p>
<div class="progressFill">
<span class="ani-puan" ani-puan="72"></span>
</div>
</div>
<div class="trustyou-progressbar pull-right">
<p class="trustyou-puan">100/39 Puan</p>
<div class="progressFill">
<span class="ani-puan" ani-puan="39"></span>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</body>
</html>
CSS
.trustyou-progressbar{
width:100px;
}
.trustyou-puan{
font-size: 13px;
color:#494949;
font-weight: 500;
}
.progressFill{
width:100%;
height:6px;
background:#222222;
}
.ani-puan{
display:block;
height:100%;
}
JQUERY
var getprogressPuan = $('.ani-puan').attr('ani-puan');
$(".ani-puan").css("width",getprogressPuan+"%");
if((getprogressPuan>0) && (getprogressPuan<=40)){
$(".ani-puan").css("background","#ca2424");
}else if((getprogressPuan>=40) && (getprogressPuan<75)){
$(".ani-puan").css("background","#d6d824");
}else if((getprogressPuan>=75)){
$(".ani-puan").css("background","#9ad204");
}
click to see demo
Use an iterator to apply your function to all elements:
$('.ani-puan').each(function() {
var getprogressPuan = $(this).attr('ani-puan');
$(this).css("width", getprogressPuan + "%");
if ((getprogressPuan > 0) && (getprogressPuan <= 40)) {
$(this).css("background", "#ca2424");
} else if ((getprogressPuan >= 40) && (getprogressPuan < 75)) {
$(this).css("background", "#d6d824");
} else if ((getprogressPuan >= 75)) {
$(this).css("background", "#9ad204");
}
});
Here is the sample page
This code just changes all elements with ani-puan class.
You need to create a jQuery component (a widget) to work with each progressbar separately.
Start by reading How to Create a Basic Plugin and then you can study jQuery UI's progressbar source code to see how they do it.
If you don't mind, you can download the jQuery UI progressbar (you don't need whole jQuery UI) and just change what you need.
Also note that HTML5 already contain component progress that already does what you need (including changing the colors).
You can also create Progress bar easily like this:
var i = 0;
var clear = setInterval(function(){
i++;
$('.progressFill').text(i+'0%');
$('.progressFill').width(i+'0%');
if(i==10)
{
clearInterval(clear);
}
},1000);
.trustyou-progressbar{
width: 100px;
background-color: #000000;
}
.trustyou-puan{
font-size: 13px;
color:#494949;
font-weight: 500;
}
.progressFill{
width: 0%;
height: 6px;
background: #15D318;
}
.ani-puan{
display:block;
height:100%;
}
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<div class="trustyou-progressbar pull-right">
<div class="progressFill">
<span class="ani-puan" ani-puan="72"></span>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</body>
</html>
here is the codepen link:http://codepen.io/kofijita/pen/WGyzQY
the $(".ani-puan") will get two elements , you should use iterator to differ them.
var $puan = $('.ani-puan');
for (var i = 0, len = $puan.length; i < len; i++) {
var $cur = $('.ani-puan').eq(i);
var getprogressPuan = $cur.attr('ani-puan');
$cur.css("width", getprogressPuan + "%");
if ((getprogressPuan > 0) && (getprogressPuan <= 40)) {
$cur.css("background", "#ca2424");
} else if ((getprogressPuan >= 40) && (getprogressPuan < 75)) {
$cur.css("background", "#d6d824");
} else if ((getprogressPuan >= 75)) {
$cur.css("background", "#9ad204");
}
}

Use variable from another method

I am making a slot machine with JavaScript and have run into an issue when I need to compare variables at the end of a scroll to see if user won or not.
Is it possible to somehow store the variable "randomArrayItem" from the method moveSlots() and use it in the go() method?
I use the moveSlots() method to move each slot separately, but I need to know the randomArrayItem it used to move it so I can compare each slots value to eachother. If they match up, the user is supposed to win.
NOTE THIS WONT RUN BECAUSE I DON"T KNOW HOW TO INSERT MY IMAGES FROM slot1,2,3. But I posted because I am only asking how to carry the randomArrayItem over to GetLucky(); ? Thanks!
var slot1 = [
'<img class="coffee" src="imgs/temp-coffee-1.jpg" alt="coffee pot icon">',
'<img class="tea" src="imgs/temp-tea-1.jpg" alt="coffee pot icon">',
'<img class="espresso" src="imgs/temp-espresso-1.jpg" alt="coffee pot icon">'
];
var slot2 = [
'<img class="coffee" src="imgs/temp-coffee-1.jpg" alt="coffee pot icon">',
'<img class="tea" src="imgs/temp-tea-1.jpg" alt="coffee pot icon">',
'<img class="espresso" src="imgs/temp-espresso-1.jpg" alt="coffee pot icon">'
];
var slot3 = [
'<img class="coffee" src="imgs/temp-coffee-1.jpg" alt="coffee pot icon">',
'<img class="tea" src="imgs/temp-tea-1.jpg" alt="coffee pot icon">',
'<img class="espresso" src="imgs/temp-espresso-1.jpg" alt="coffee pot icon">'
];
function GetLucky(){
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function go(){
addSlots();
moveSlots($('#slot_a'));
moveSlots($('#slot_b'));
moveSlots($('#slot_c'));
// NEED TO COMPARE var randomArrayItem from _a, _b, _c to see if they match... ideas???
}
function moveSlots(el){
var time = 500;
time += Math.round(Math.random()*2000);
el.stop(true,true);
var randomArrayItem = getRandomInt(0, 2);
var marginTop = (-7 * (100)) - (randomArrayItem * 100 ); //change 100 to height placeholder
el.animate(
{"margin-top":marginTop+"px"},
{'duration' : time, 'easing' : "easeInOutQuint"}
);
}
function addSlots(){
for(i=0; i<20; i++){
$('#slot_a').append("<div class='content'>" + slot1[getRandomInt(0,2)] + "</div>");
$('#slot_b').append("<div class='content'>" + slot2[getRandomInt(0,2)] + "</div>");
$('#slot_c').append("<div class='content'>" + slot3[getRandomInt(0,2)] + "</div>");
}
}
}
body{
background-color:white;
padding:50px;
margin:50px;
}
.slots {
font-size:10px;
font-family:arial,helvetica,sans-serif;
overflow:hidden;
width:100px;
height:100px;
border:1px solid black;
float:left;
}
.slots .wrapper{
width:100px;
}
.slots .slot{
width:100px;
height:100px;
text-align:center;
}
.slot .content {
width:100px;
height:100px;
color:#000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
</html>
<body>
<script src="js/jQuery_v1.12.3.js" type="text/javascript"></script>
<script src="js/jquery.easing.1.3.js" type="text/javascript"></script>
<script src="js/scripts.js" type="text/javascript"></script>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<div style="width:310px">
<div class="slots" id="slots_a">
<div class="wrapper" >
<div id="slot_a" class='slot'><!-- <img src="imgs/temp-tea-1.jpg" alt="coffee pot icon"> --></div>
</div>
</div>
<div class="slots" id="slots_b">
<div class="wrapper" >
<div id="slot_b" class='slot'><!-- <img src="imgs/temp-coffee-1.jpg" alt="coffee pot icon"> --></div>
</div>
</div>
<div class="slots" id="slots_c">
<div class="wrapper" >
<div id="slot_c" class='slot'><!-- <img src="imgs/temp-espresso-1.jpg" alt="coffee pot icon"> --></div>
</div>
</div>
<div style="text-align:center">
<input type="button" value="spin!" onClick="GetLucky();" style="margin-top:4px;">
</div>
</div>
</body>
Hard to explain but you will see below.
Try to return the randomArrayItem from move slots and trigger the execution of go by calling it go();
function GetLucky(){
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function go(){
addSlots();
randomArrayItem1 = moveSlots($('#slot_a'));
randomArrayItem2 = moveSlots($('#slot_b'));
randomArrayItem3 = moveSlots($('#slot_c'));
if (randomArrayItem1 == randomArrayItem2 && randomArrayItem2 == randomArrayItem3) console.log('win');
}
function moveSlots(el){
var time = 500;
time += Math.round(Math.random()*2000);
el.stop(true,true);
var randomArrayItem = getRandomInt(0, 2);
var marginTop = (-7 * (100)) - (randomArrayItem * 100 ); //change 100 to height placeholder
el.animate(
{"margin-top":marginTop+"px"},
{'duration' : time, 'easing' : "easeInOutQuint"}
);
return randomArrayItem;
}
function addSlots(){
for(i=0; i<20; i++){
$('#slot_a').append("<div class='content'>" + slot1[getRandomInt(0,2)] + "</div>");
$('#slot_b').append("<div class='content'>" + slot2[getRandomInt(0,2)] + "</div>");
$('#slot_c').append("<div class='content'>" + slot3[getRandomInt(0,2)] + "</div>");
}
}
go();
}
You can store variables by having a function return a value and have that function on the right hand of an assignment operation.
For instance:
var randomInt = getRandomInt();
EDIT: That said, if randomInt is inside a function, another function will not be able to access it. Example:
function i() { var x = 7; }
var a = x+x;
Var a in the above code will be undefined since the variable is not defined globally (only within its function)
Just a general note too...your code never seems to actually executes go(). It only defines it via function go() etc.

Get the clients screen size and resize the image to it

i am trying to get the users screen size and resize an image to fit their screen size my current code works but only in firefox. In IE and Chrome the image never resize could somebody please help me?
http://jsfiddle.net/dwcribbs/ZK4tK/2/
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../style.css">
<script type="text/javascript" src="../javascript.js"></script>
<script>
window.onload = function(){
var w =screen.availWidth - 20 + "px";
var h =screen.availHeight - 80 + "px";
document.getElementById('full').style= "height:" + h + ";" + "width:" + w; +";";
alert(h+w);
checkCookie();
document.getElementsByClassName('box1')[0].addEventListener('click', correct, false);
document.getElementsByClassName('box1')[0].addEventListener('mouseover', shade, false);
document.getElementsByClassName('box1')[0].addEventListener('mouseout', unshade, false);
document.getElementsByClassName('bg')[0].addEventListener('click', wrong, false);
function shade()
{
document.getElementById('button').style= "background-color: #ADD8E6; opacity:.4;";
}
function unshade()
{
document.getElementById('button').style= " ";
}
function loc()
{
var lo = "OS2.html";
return lo;
}
}
</script>
</head>
<body>
<div style="color: red;" onclick=" alert('Open Microsoft Power Point without *searching* for it\nSave it in the documents library (using backstage-view, save as), with the default name');" id="help">
<center>
?
</center>
</div>
<div class="wrap">
<img id="full" style = "height: 500px; width: 500px;"class="bg" src = "../Pic/desktop.png" >
<div id="button" style=" " class="box box1"></div>
</div>
</body>
</html>
Thanks!
Instead of
document.getElementById('full').style = "height:" + h + ";" + "width:" + w;
+";"; // Useless NaN
you should use [Demo]
var s = document.getElementById('full').style;
s.height = h;
s.width = w;
or [Demo]
document.getElementById('full')
.setAttribute('style', "height:" + h + ";" + "width:" + w);

Categories