What are some ways to relocate an element that has been styled using a CSS stylesheet?

I need to make an image move on a web page. The code below shows how I can use JavaScript to accomplish this task:

<html>
<head>
    <title>Snake</title>
    <script type="text/javascript" src="snake.js"></script>
    <!-- <link type="text/css" href="snake.css"> -->
</head>
<body onKeyPress="ProcessKeypress(event);">
    <p><img id="snake" style="z-index: 0; left: 300px; position: absolute; top: 250px" 
    float=top border=0 hspace=0 src="snake.gif"></p>
</body>

But now, I want to use CSS to style the image element. However, when I modify the code as shown below, the movement functionality no longer works:

<html>
<head>
    <title>Snake</title>
    <script type="text/javascript" src="snake.js"></script>
    <link type="text/css" href="snake.css">
</head>
<body onKeyPress="ProcessKeypress(event);">
    <p><img id="snake" src="snake.gif"></p>
</body>

@CHARSET "UTF-8";
img {
z-index: 0;
left: 300px; 
position: absolute; 
top: 250px;
float: top;
border: 0;
hspace: 0;
}

The JavaScript code snippet provided below is what I am currently using to animate the image. Any suggestions or guidance would be greatly appreciated.

function moveObj(name, Xpix, Ypix) 
{    
    obj = document.getElementById(name);

    px = parseInt(obj.style.left) + Xpix;       
    py = parseInt(obj.style.top) + Ypix;
    obj.style.left = px;
    obj.style.top = py;
}

function ProcessKeypress(e)
{
    var myObj = 'snake';
    var moveBy = 10;

    if(e.keyCode === 97) {
        moveObj(myObj, -moveBy, 0);
    }
    else if(e.keyCode === 100) {
        moveObj(myObj, moveBy, 0);
    }
    else if(e.keyCode === 115) {
        moveObj(myObj, 0, moveBy);
    }
    else if(e.keyCode === 119) {
        moveObj(myObj, 0, -moveBy);
    }
}

Answer №1

When using obj.style.left, you can only access the style properties defined in inline.

UPDATE

Check out the pure JavaScript Solution

Function: getStyleProp() to retrieve the current applied style [Source]

function getStyleProp(elem, prop){
    if(window.getComputedStyle)
        return window.getComputedStyle(elem, null).getPropertyValue(prop);
    else if(elem.currentStyle) return elem.currentStyle[prop]; //IE
}

Function: moveObj()

function moveObj(obj, Xpix, Ypix) {  
    obj.style.left = parseInt(getStyleProp(obj,'left')) + Xpix+"px";
    obj.style.top= parseInt(getStyleProp(obj,'top')) + Ypix + "px";
}

Function: ProcessKeypress()

function ProcessKeypress(e) {
    var myObj = document.getElementById("snake");
    var moveBy = 10;
    switch(e.charCode) {
        case 97: moveObj(myObj, -moveBy, 0); break;
        case 100: moveObj(myObj, moveBy, 0); break;
        case 115: moveObj(myObj, 0, moveBy); break;
        case 119: moveObj(myObj, 0, -moveBy); break;            
    }
}    

I also provided a jQuery solution: Demo

Function moveObj

function moveObj(obj, Xpix, Ypix) {    
    obj.css('left', parseInt(obj.css('left')) + Xpix);       
    obj.css('top', parseInt(obj.css('top')) + Ypix);
}

Function ProcessKeypress

function ProcessKeypress(e) {
    var myObj = $("#snake"); //Caching for better performance
    var moveBy = 10;
    switch(e.charCode) { 
        case 97: moveObj(myObj, -moveBy, 0); break;
        case 100: moveObj(myObj, moveBy, 0); break;
        case 115: moveObj(myObj, 0, moveBy); break;
        case 119: moveObj(myObj, 0, -moveBy); break;            
    }
}

Event Trigger attached to document instead

$(document).on('keypress', ProcessKeypress);

Answer №2

It seems like there may have been a mistake in your code, as the link tag for linking your CSS file needs to be closed properly.

<link rel="stylesheet" type="text/css" href="path/to/your/style.css" />

However, let's focus on the main issue at hand. This is a repost, so I will mark it as such. Please check out this helpful resource for more information: Why is element.style.left returning NaN?

Hopefully, this clears up any confusion. It certainly helped me understand your code better. Best of luck with your project!

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

Creating a new row in a Tabulator component in React and retrieving the data

I have incorporated the react-tabulator library into my project and I am looking for guidance on how to dynamically add new rows once the tabulator has been rendered. Ideally, I would like to include a button below the tabulator that enables users to add a ...

What is the best way to retrieve all the keys from an array?

I am looking to retrieve the address, latitude, and longitude data dynamically: let Orders= [{ pedido: this.listAddress[0].address, lat: this.listAddress[0].lat, lng: this.listAddress[0].lng }] The above code only fetches the first item from the lis ...

Show an image based on a query parameter

Currently, I am developing a PHP project and I am facing an issue with loading an image from a query string. Here is the code snippet I am using: <img src="load_image.php?name=Profile_Photo_Small" /> Is there anyone who can help me out with this pro ...

A comprehensive guide on implementing form array validations in Angular 8

I am currently using the formArray feature to dynamically display data in a table, which is working perfectly. However, I am facing difficulty in applying the required field validation for this table. My goal is to validate the table so that no null entry ...

Incorporate Angular directives within a tailor-made directive

I just started using a fantastic autocomplete directive called Almighty-Autocomplete. However, I feel like it's missing some features. The basic structure of the directive is as follows: .directive('autocomplete', function () { var index ...

Prevent one individual cell in a table from dictating the overall table width

A B A B A X A B In a contained block with a fixed width of 400px, there is a table. When the browser width drops below 421px, the width of the containing block changes to 95%. The cells labeled "A" and "B" contain simple text. There is one cel ...

Designing HTML components with cohesive HTML and CSS

Check out this live demo I'm working on creating modules that have consistent markup and CSS, allowing for flexibility in size adjustments. I want to use the same module in various sections like utilities, footer, or header. My goal is to structure ...

"Implement a delay in key presses using the setTimeout function to create a pause

I'm having trouble with a function that reloads messages within a div using a timer. I've tried several methods to create a stable timer that runs consistently every 4 seconds, but so far each attempt results in the timer maxing out and running m ...

Implementing text wrapping within input elements for optimal print.css layout

Can you help me with a print.css issue I'm experiencing? I am currently working on my print stylesheet and I've encountered a challenge where I need to word wrap input fields to ensure all the text is displayed correctly. Despite trying various ...

Tips on extracting variables from JMeter Selenium WebDriver

Currently, I am dealing with a token that is being returned in the body of a web page. WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[contains(@name,'RequestVerificationToken')]")).getText(); This token is what I need to extract: ...

Instructions for repositioning a popup to a specific area on the screen: How can a popup be shifted to anchor on

Hey there, I wanted to share my website www.livehazards.com with you. Currently, I am working on relocating the popup box linked to each earthquake to the bottom right corner of the screen. Below is the code related to the popup box: .mapboxgl-popup-co ...

The automatic sliding feature stops functioning once the controls have been clicked

When using the boxslider, the autosliding feature functions correctly initially. However, after manually clicking on the left and right arrow controls, the auto sliding stops working. See below for my code snippet: <ul id="slider-assocoates"> ...

What is the best method for managing file storage and retrieval in web applications that only run on the client-side?

I'm currently working on an application where users can create their own data. Without a backend or database, all the information is stored within the user's session. My preferred solution involves: User interacts with the app, clicks "Save", ...

What could be the reason behind my Vue custom directives not functioning as expected?

I'm brand new to Vue and very inexperienced with custom directives. I'm attempting something basic, but it doesn't seem to be working correctly. Can someone please help me figure out what's wrong? Thank you in advance! I have created tw ...

Update the less mixin

I attempted to eliminate the border radius from all Bootstrap elements by creating a custom-mixins.less file with the following lines in it. My intention was for these lines to overwrite the original .border-radius mixin, but unfortunately, it did not work ...

What is the method for transmitting a message from localhost to a React frontend?

I am currently running a WebSocket server that is receiving streams of messages from an MQTT source. These messages are then sent to a localhost server on port 8080. The messages being received are actually a stream of random numbers. Below is the Python ...

Achieving consistent text alignment in HTML and CSS without relying on tables

As I delve into the world of HTML and CSS, I've taken a traditional approach by crafting a login page complete with three input controls (two text inputs and one button). To ensure proper alignment of these elements, I initially turned to the trusty & ...

DIV is unable to detect SVG elements inside it

What could be causing the <div> not to automatically adjust its height based on the inner <svg> element in this particular situation? CSS #curve-svg { height: auto; max-width: 400px; position: relative; border: 1px solid red; svg { ...

What would be the ideal alternative if the Google Ajax API is unavailable, given that Google does not allow for local installation?

On my website, I include the following script: ... <script type="text/javascript" src="https://www.google.com/jsapi"></script> ... This particular script is from Google and is used to dynamically load other resources, such as the Google Chart ...

Embracing the power of dynamic imports in Next.js 10 with SDK integration for

I attempted to dynamically import the TRTC SDK using Next.js 10: const TRTC = dynamic(() => import('trtc-js-sdk').then((module) => module.NamedExport), { ssr: false }); However, I encountered an error stating "TRTC.createClient is not a co ...