Modify image upon mobile rotation using JavaScript, similar to the functionality seen on getmoju.com

I am seeking guidance as I am unsure of where to begin. I have a collection of 25 images for the same position, and I want to dynamically change the image displayed on an iPhone Safari browser based on the degree of change in mobile position from left to right. Any assistance or suggestions would be greatly appreciated.

Here is the code snippet I have to obtain the rotation rate:

window.ondevicemotion = function(event) {  
    var accelerationX = event.accelerationIncludingGravity.x;  
    var accelerationY = event.accelerationIncludingGravity.y;  
    var accelerationZ = event.accelerationIncludingGravity.z;  
} 

I have a concrete example that illustrates exactly what I am trying to achieve.

EDIT:-

I have attempted some code.

<script type="text/javascript">

var x = 0, y = 0,
    vx = 0, vy = 0,
    ax = 0, ay = 0;

var sphere = document.getElementById("sphere");

if (window.DeviceMotionEvent != undefined) {
    window.ondevicemotion = function(e) {
        ax = event.accelerationIncludingGravity.x * 10;
        ay = event.accelerationIncludingGravity.y * 10;

    }

    setInterval( function() {
        var landscapeOrientation = window.innerWidth/window.innerHeight > 1;
        if (landscapeOrientation) {
            vx = vx + ay;
            vy = vy + ax;
        } else {
            vy = vy - ay;
            vx = vx + ax;
        }
        vx = vx * 0.98;
        vy = vy * 0.98;
        y = parseInt(y + vy / 50);
        x = parseInt(x + vx / 50);

        boundingBoxCheck();
        document.getElementById("sphere").innerHTML = x;
        sphere.style.right = y + "px";
        sphere.style.left = x + "px";
        var screenWidth=screen.width;
        var imageCount=24;
        var medianImageChange=screenWidth/imageCount;
        var count=1;

        for (i = 0; i < imageCount; i++) {
            var medianImageChange=medianImageChange*count;
            if((medianImageChange)<x || medianImageChange==x){
                document.getElementById("innerHTML").innerHTML = '<img class="change'+count+'" id="change'+count+'" src="https://cf0.getmoju.com/f/Sq6ZUEom-lkB_'+i+'.jpg" />';
            }
            count++;
        }

    }, 25);
} 


function boundingBoxCheck(){
    if (x<0) { x = 0; vx = -vx; }
    if (y<0) { y = 0; vy = -vy; }
    if (x>document.documentElement.clientWidth-20) { x = document.documentElement.clientWidth-20; vx = -vx; }
    if (y>document.documentElement.clientHeight-20) { y = document.documentElement.clientHeight-20; vy = -vy; }

}

</script>

HTML:-

<div id="content">
    <h1>Accelerometer Javascript Test</h1>
    <div id="sphere"></div>
        <div id="innerHTML"></div>
</div>

However, the desired outcome is not being achieved. Can anyone offer assistance, please?

Answer №1

After a full day of hard work, I finally found the solution I was looking for.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Move the Ball</title>
<meta name="viewport" content="width=device-width,user-scalable=no" />
<script src="http://debug.phonegap.com/target/target-script-min.js#accelerometer"></script>
<style>
#no {
    display: none;  
}
.hide{display:none;}
#ball {
    width: 20px;
    height: 20px;
    border-radius: 10px;
    -webkit-radius: 10px;
    background-color: red;
    position:absolute;
    top: 0px;
    left: 0px;
}
</style>
<script type="text/javascript" src="moju/jquery-1.11.2.min.js"></script>
</head>

<body>
<div id="content">
    <h1>Move the Ball</h1>
    <div id="yes">
        <p>Move your device to move the ball. This sample is using Device Orientation and Motion API compatible with iOS since 4.2</p>
        <p>Maintain your device in portrait orientation for better results (you can lock it)</p>

        <--- Omitted rest of HTML content for brevity --->
        
</div>
<script>
/*
Curious about the code? Great! Welcome to this code ;)
Feel free to copy and use this code
If you are going to blog or tweet about it or if you are going to create a better
code, please maintain the link to www.mobilexweb.com or @firt in Twitter.
*/

<--- JavaScript code omitted for brevity --->

</script>

</body>
</html>

Hopefully, someone else will find this information helpful as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Move objects on the webpage by dragging and dropping them

My goal is to create a website with drag-and-drop functionality for elements, similar to Wordpress widgets. Users should be able to easily add text boxes to different areas on the site by simply dragging and dropping them. If necessary, they can also choos ...

Implement a click event using jQuery specifically for Internet Explorer version 7

How can I add an onclick attribute using jQuery that is compatible with IE7? So far, the following code works in browsers other than IE8 and Mozilla: idLink = Removelst(); var newClick = new Function(idLink); $(test1).attr('onclick', null).clic ...

Utilizing AngularJS for toggling data with ng-click

In my project, I have a unique issue with a list item that toggles a modal and sets a parameter using ng-click. Strangely, when calling a specific function in another location, Course.SelectedCourse returns as undefined, even though Course.ID has a valid ...

Swiper.IO pagination indicators not displaying

Why is the pagination not showing up on the image carousel I created with Swiper? Despite being in the DOM, it has a height of 0 and manual changes have no effect. Any suggestions? import Swiper from '../../vendor/swiper.min.js'; export default ...

What is the best way to create a mirror effect on one div by clicking another div?

I have created a schedule grid and I am looking for a way to allow users to click on the UK hour and then have the corresponding U.S time highlighted. Is there a CSS solution for this? The functionality I need is to be able to select multiple hours. I have ...

Waiting for the function to finish in both the caller and the callee

One of the classes in my service is named: Test. Inside this Test Class, there is a method called: getMe(). Within the getMe function, I have 3 await statements where the 2nd one relies on the result from the first one, and the third one depends on the a ...

Custom Native Scrollbar

Currently, there are jQuery plugins available that can transform a system's default scroll bar to resemble the iOS scroll bar. Examples of such plugins include . However, the example code for these plugins typically requires a fixed height in order to ...

Is it possible to modify the local reference point of an object in three.js?

Is there a method to readjust the center point of an STL file once it has been relocated or turned? For example, if the original rotation of my object is set at (0,0,0), and then I rotate it to (20,70,90) degrees, is it possible to modify the local origi ...

What is the best way to establish a limit on the number of characters that can be entered into an input field in a React form?

Currently, I am creating a tool to check the strength of passwords based on their length. However, I am unsure of how to precisely determine if a password falls within specific length ranges such as "between 5 and 10 characters" or "between 20 and 30 cha ...

Javascript code experiences a shift in two different styles within a single conditional statement

I'm new to web design and I'm having trouble getting this code to work properly. Can anyone help me fix it so that both styles are applied correctly? // Access the sign_up modal window var modal = document.getElementById('id01'); // A ...

Can you help identify the issue in this particular ajax code?

Here is the code I wrote to check if a username exists in the database using Ajax. However, I am facing an issue where the input text from the HTML page is not being sent to the checkusername.php file via $_POST['uname'];. I have tried multiple s ...

Issue - The command 'bower install' terminated with Exit Status 1

During my journey through the angular-phonecat tutorial, a frustrating error popped up right after I executed the npm install command: I even checked the log file, but it just echoed the same error message displayed in the console. What's the piece o ...

Detecting Changes in Angular2 Component Attributes via Observables

When working with Angular 2 components that have input attributes defined using @Input, how can I create an observable to track changes to those input attributes (not to be confused with user input from a form)? export class ExampleComponent implement OnC ...

Transmitting a sequence of JSON information from php to JavaScript,

I am struggling to fetch a series of JSON data from PHP to my JavaScript file. Initially, I have multiple JSON data stored in an array in PHP, and I am echoing each one by looping through the array in my JavaScript file. <?php $result = array('{ ...

Retrieve the text from an ajax response that includes the <tag> element

I have created a simple piece of code to fetch news from an RSS page. Below is the code snippet: this.loadRecentNews = function loadRecentNews() { $.get("http://rss.nytimes.com/services/xml/rss/nyt/GlobalHome.xml", function (data) { ...

What is the best way to share props with all routes in vue.js?

I need to make sure that all components have access to the BASE_URL variable. Here is an example of my App.js: <template> <router-view></router-view> </template> <script> import addJoke from './components/addJoke.vue&ap ...

Node - ensure that each API call finishes before initiating the next one

Currently, I am encountering an issue with my POST request within the 'add-users' route. I have initialized an array named success and aim to trigger the next API call once a response is received. It seems that the problem lies in sending too ma ...

Is JSON parsing feature supported by IOS 5 built in API compatible with older version phones?

With the introduction of IOS 5, new built-in APIs have been included to streamline the process of reading and writing JSON. The question arises - will an app built using these APIs be compatible with devices running older versions of IOS? ...

The JavaScript function may fail to work if the AJAX request is not completed

Upon completion of my ajax request, my function does not seem to be functioning as expected. Here is the script I am using: <script> function sendmsg(id,msg){ alert('id is'+id+'and msg is '+msg); } <scr ...

What is the method for transforming a regular expression into every conceivable scenario?

transform a regular expression into all potential combinations For Instance: If the input is 1.9856[1-4], it should generate values like 98561, 98562, 98563, 98564 If the input is 2.98[4-5]65, it should output values 98465, 98565 ...