Mastering the Javascript ++ and += Operators

I'm struggling with a simple movement engine I created. When the Up key is pressed, a function moves a small div up, and when the Down key is pressed, it does the opposite. I suspect the issue lies with the += in the Down() function, as changing it to -= resolves the problem. However, I can't seem to identify what might be conflicting with the function.

My problematic area is marked by a comment at the bottom.

    var interval = '';
    var key = false;
    var interval1 = '';
    var key1 = false;
    $(document).keydown(function(e) {
    if(e.which === 38) {
        if(key === false){
            interval = setInterval(function(){Up()},20)
        key = true;
        }
    }
    if(e.which === 40) {
        if(key1 === false){
            interval1 = setInterval(function(){Down()},20)
        key1 = true;
        }
    }
    });
    $(document).keyup(function(e) {
    if(e.which === 38) {
        clearInterval(interval)
        key = false;
    }
    if(e.which === 40) {
        clearInterval(interval1)
        key1 = false;
    }
    });

    document.getElementById('Jumper').style.top = '46%';

    var Top = parseInt(document.getElementById('Jumper').style.top);
    var Topp = parseInt(document.getElementById('Jumper').style.top);

    function Up(){
if(Top > 0){
Top = parseInt(document.getElementById('Jumper').style.top);
    Top -= 0.2;
    document.getElementById('Jumper').style.top = Top+'%';
    }
    }

    function Down(){
if(Topp > 0){
Topp = parseInt(document.getElementById('Jumper').style.top);
    Topp += 0.2;                             //<--PROBLEM
    document.getElementById('Jumper').style.top = Topp+'%';
    }
    }
#Jumper{
position: absolute;
    top: 46%;
    left: 48%;
    height: 8%;
    width: 4%;
    background-color: red;
    opacity: 1;
}
<div id='Jumper'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

I would appreciate any insights on how to resolve this issue.

Check out this fiddle: https://jsfiddle.net/Tobsta/2gnoq5hx/

Answer №1

It is important to remember that when extracting values from HTML elements, using parseFloat() instead of parseInt is crucial for accurate results:

Topp = parseFloat(document.getElementById('Jumper').style.top);

https://jsfiddle.net/7jxcw8md/1/

Answer №2

It all went wrong because of this single line:

Topp = parseInt(document.getElementById('Jumper').style.top);

Big thanks to Juhana for catching that mistake.

Here's the corrected code snippet:

var interval = '';
var key = false;
var interval1 = '';
var key1 = false;
var interval2 = '';
var key2 = false;
var interval3 = '';
var key3 = false;
$(document).keydown(function(e) {
    if(e.which === 38) {
        if(key === false){
            interval = setInterval(function(){Up()},20)
        key = true;
        }
    }
    if(e.which === 40) {
        if(key1 === false){
            interval1 = setInterval(function(){Down()},20)
        key1 = true;
        }
    }
    if(e.which === 37) {
        if(key2 === false){
            interval2 = setInterval(function(){Left()},20)
        key2 = true;
        }
    }
    if(e.which === 39) {
        if(key3 === false){
            interval3 = setInterval(function(){Right()},20)
        key3 = true;
        }
    }
});
$(document).keyup(function(e) {
    if(e.which === 38) {
        clearInterval(interval)
        key = false;
    }
    if(e.which === 40) {
        clearInterval(interval1)
        key1 = false;
    }
    if(e.which === 37) {
        clearInterval(interval2)
        key2 = false;
    }
    if(e.which === 39) {
        clearInterval(interval3)
        key3 = false;
    }
});

document.getElementById('Jumper').style.top = '46%';
document.getElementById('Jumper').style.left = '48%';

var a = parseInt(document.getElementById('Jumper').style.top);
var b = parseInt(document.getElementById('Jumper').style.left);

function Up(){
if(a > 0){
    a -= 1;
    document.getElementById('Jumper').style.top = a+'%';
    }
}

function Down(){
    if(a < 92){
a += 1;
    document.getElementById('Jumper').style.top = a+'%';
    }
}

function Left(){
if(b > 0){
    b -= 0.5;
    document.getElementById('Jumper').style.left = b+'%';
    }
}

function Right(){
    if(b < 96){
b += 0.5;
    document.getElementById('Jumper').style.left = b+'%';
    }
}
#Jumper{
position: absolute;
    top: 46%;
    left: 48%;
    height: 8%;
    width: 4%;
    background-color: red;
    opacity: 1;
}
<div id='Jumper'></div>

Alternatively, check out the js fiddle link below:

http://www.jsfiddle.net/Tobsta/2gnoq5hx/2

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

Tips for dragging and dropping a file attachment directly into your web browser

Google has recently introduced this feature to Gmail, and it doesn't need you to download any additional plugins. This feature is compatible with both Firefox and Chrome browsers, but unfortunately not with Internet Explorer. ...

Show and hide elements using jQuery's toggle functionality

Here is some HTML code that I have: <div id="text-slide"><ul class="menu"> <li><a href="" id="toggle1">Webdesign</a> </li><div class="toggle1" style="display:none;width:45%; position:absolute;left: 16%; top:0;"> ...

A guide to integrating ffmpeg with NuxtJS

I am completely new to Nuxt and currently in the process of migrating a Vue application that generates gifs using ffmpeg.wasm over to Nuxt.js. However, every time I try to access the page, the server crashes with the following error message: [fferr] reques ...

What is preventing me from creating a table with a filter option?

I've been attempting to create a filterable table similar to this example. I followed the code from the w3schools website, but unfortunately, it does not seem to be working for me. When I type in text, nothing gets filtered. <div id="users-tab ...

Guide on Developing a JavaScript Library

After creating several JavaScript functions, I noticed that I tend to use them across multiple projects. This prompted me to take things a step further and develop a small JavaScript Library specifically for my coding needs. Similar to popular libraries l ...

How can a pop-up be positioned to appear in the right bottom corner using jQuery

Is there a way to position a pop-up at the bottom right corner of the window? I have code that centers the pop-up in the window, but I'm looking to place it specifically at the bottom right corner. $(id).css('top', winH - $(id).height()); ...

Enhancing jQuery OrgChart with personalized AJAX request headers

Is there a way to set request headers on an ajax call using the OrgChart library? I attempted the following: $('#chart-container').orgchart({ 'data' : '/api/v1/profiles/orgchart/', 'beforeSend&ap ...

Invoke a TypeScript function within JavaScript code

As a result of the limitations of IE10 and earlier versions, I find myself in need to reimplement the Import/Upload functionality that I had initially created since FileReader is not supported. After some consideration, I have opted to utilize an iFrame in ...

How can I retrieve an array of data from Firebase Firestore using React Native?

I have been working on fetching Array data from Firebase Firestore. The data is being fetched successfully, but it is all displaying together. Is there a way to fetch each piece of data one by one? Please refer to the image for a better understanding of ...

The output of jQuery('body').text() varies depending on the browser being used

Here is the setup of my HTML code: <html> <head> <title>Test</title> <script type="text/javascript" src="jQuery.js"></script> <script type="text/javascript"> function initialize() { var ...

Retrieve a solitary row of information from a MySQL column

Here is an example of a MySQL database with the main table containing fields such as id, name, age, and photos: Table main: 3 John 22 photo1.jpg photo2.jpg photo3.jpg ph ...

Replace anchor text using jQuery

I'm currently working on implementing a like system, but I've encountered an issue. When a user clicks the like button, the text should change from "Like" to "Remove Like". The data is being fetched from a PHP query, so there are multiple items ...

How to create a clickable background image with an overlaid hyperlink?

I am looking for a way to make a logo appear clickable, even though it is just a background image. Unfortunately, I am unable to modify the HTML code, so I am limited to making changes in the CSS only. This is for a blog hosted on Wordpress.com, where HTML ...

Retrieve every span element within the Hidden field by utilizing JQuery

Recently I started using Jquery and I have a hidden variable that contains all span tags within it. Can anyone guide me on how to access all the span elements inside the hidden field value? For instance, if there are 3 span elements within the hidden fiel ...

Conceal email address within HTML code

Similar Inquiry: What is the best way to hide an email address on a website? I've been contemplating ways to keep my email address secure on my website, including using AJAX to request it from the server after key validation and then simulating H ...

Exploration of JavaScript Interview Questions

I need help creating a JavaScript function that will be triggered on button click, but instead of targeting the button directly, it should target a div element by its class. How can I achieve this? <body> <div class="content"> <butto ...

Error: Unhandled promise rejection: [object Boolean]

I am encountering an issue while trying to secure a route in my Angular application. Despite what I believe to be the correct implementation, I am facing an error message when the negative scenario is triggered: ERROR Error: Uncaught (in promise): [object ...

The word-wrap property does not function properly in the <small> element or any other HTML elements

My code has a small issue with the word-wrap property not working as expected. When I change it to a div element, it works fine but I need to use the small or another specified element. Does anyone have any ideas why the word is not breaking and what could ...

Multiple file uploads with dynamic image previews and individual names

Currently, I'm facing an issue with displaying a preview and the name of images before uploading via ajax. To show the preview, I am using the File Read API along with the ".name" method to display the file name. However, all the previews are showing ...

Access another key within an object

Here's a code snippet from my module: exports.yeah = { hallo: { shine: "was", yum: this.hallo.shine } } In the above code, I'm attempting to reference the shine property in yum: this.hallo.shine However, when I run the script, ...