JavaScript class name modifications are not functioning as expected

Testing a sprite sheet on a small web page I created. The code for each sprite in sprites.css is structured like this...

.a320_0 {
   top: 0px;
   left: 0px;
   width: 60px;
   height: 64px;
   background: url("images/sprites.png") no-repeat -787px -398px;
}

The layout of my test page is as follows...

var i = 0

function imageChange() {
  setTimeout(function() {
    var hdg = i * 15;
    document.getElementById('image').className = "a320_" + hdg;
    i++;
    if (i < 24) {
      imageChange();
    }
  }, 1000)
}
imageChange()
<div id='imageContainer'>
  <div id='image'></div>
</div>

Verified that the class name changes during the loop and matches classes in my style sheet. Both sprites.css and sprites.png are located in the images folder within the same directory as my page.

When directly applying a rule from the style sheet to the page with #image, I can display the specific image, confirming correct sprite coordinates. However, placing the styles into the actual css file or using .className = does not yield the expected result. Previously functional setup now encountering issues, seeking assistance...

Answer №1

Make sure to use

document.getElementById("image").classList.add("a320_" + hdg);
.

var x = 0;

function changeImage() {
  setTimeout(function() {
    var hdg = x * 15;
    document.getElementById("image").classList.add("a320_" + hdg);
    x++;
    if (x < 24) {
      changeImage();
    }
  }, 1000);
}

changeImage();
.a320_0 {
  top: 0px;
  left: 0px;
  width: 60px;
  height: 64px;
  background: url("https://source.unsplash.com/random") no-repeat -787px -398px;
}
<div id='imageContainer'>
  <div id='image'></div>
</div>

Check it out on Codepen

Answer №2

Although your script appears to be accurate, there seems to be a significant syntax error causing it to not produce the intended outcome.

When applying a class name to an HTML element using JavaScript, the correct syntax is as follows:

selector.property.action("property value");

For instance, your code should look like this:

document.getElementById('image').classList.add("a320_" + hdg);

The correction only needs to be made in the javascript section:

var i = 0

function imageChange() {
  setTimeout(function() {
    var hdg = i * 15;
    document.getElementById('image').classList.add("a320_" + hdg);
    i++;
    if (i < 24) {
      imageChange();
    }
  }, 1000)
}
imageChange()

I trust this information proves beneficial!

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

The Drop Down Menu feature in Bootstrap is malfunctioning within the context of a NextJS project

I've built a NEXT.JS application using VS Code. The issue I'm facing is with the drop down menu in the navigation bar - it's not sliding down to display the menu when clicked. Here is the code I'm working with: const loggedRouter = () ...

The return type of a server-side component in NextJS 14 when it is asynchronous

When using NextJS 14, I encountered a problem with the example provided in the documentation. The example is within the Page component, typically typed as NextPage. However, this type does not support the use of async await server components. In my case, ...

A div positioned to the left is placed beneath another div

I am faced with a design challenge involving two divs. The first div is floated left, while the second div is floated right. In order to achieve a responsive layout, I need the first div to go under the second div when the viewport changes. Both divs conta ...

Simple yet perplexing JavaScript within an Angular directive

In the tutorial, the author explains that each element in the stars array contains an object with a 'filled' value, which is determined as true or false based on the scope.ratingValue received from the DOM. directive('fundooRating', fu ...

Guide on generating a dynamic loop in JavaScript using the group name as a variable

I have been attempting to organize a group, dynamically ungroup it, and then create a loop with each element of the group. Despite reviewing multiple examples, I have not been able to solve the following issue: The grouping is done based on the "tipo" pro ...

Passing JSON information through PatternLab

Incorporating an atomic pattern and passing data from a JSON array is my goal. Below are the code snippets and JSON file. anchor-link.mustache <a href="{{ url }}" class="{{ class }}">{{ label }}</a> footer-nav.mustache <ul class="menu ve ...

Encountered an issue with instafeed.js due to CORS policy restrictions

Trying to implement an API that provides JSON data for use in a function. Required Imports: Importing Jquery, instafeed.min.js, and the API (instant-tokens.com). <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js& ...

Responses were buried beneath the inquiries on the frequently asked questions page

My FAQs page is in pure HTML format. The questions are styled with the css class .pageSubtitle, and the answers have two classes: .p1 and .p2. Here's an example: <p class="pageSubtitle">Which Award should I apply for?</p> <p class="p1" ...

Ways to maneuver the vehicle by using the left or right key inputs

I am a beginner with canvas and game development. I am currently working on a project where a car moves in a straight line, but I want to add functionality for the car to turn anti-clockwise when the left key is pressed, and clockwise when the right key is ...

"Incorporating Node.js (crypto) to create a 32-byte SHA256 hash can prevent the occurrence of a bad key size error triggered by tweetnacl.js. Learn how to efficiently

Utilizing the crypto module within node.js, I am creating a SHA256 hash as shown below: const key = crypto.createHmac('sha256', data).digest('hex'); However, when passing this key to tweetnacl's secretbox, an error of bad key siz ...

What is the process of sending a file from a remote URL as a GET response in a Node.js Express application?

Situation: I am working on a Multi-tier Node.js application with Express. The front end is hosted on an Azure website, and the back end data is retrieved from Parse. I have created a GET endpoint and I want the user to be able to download a file. If the f ...

Upgrading object based on dynamic data shifts in Vue using Vuex

My current task involves updating data in a component based on the selection made from a tabs list at the top of the page. The data is sourced from a Vuex data store, and after conducting tests on the data store, everything appears to be functioning correc ...

Python Selenium fails to retrieve table data

I am encountering an issue where the print statement at the end of my code returns NONE. I aim to store values at every 6th spot in each row, which is functioning correctly. However, when I attempt to print(self.mystr) at the end, it does not give me a val ...

Tips for resolving the "Page Not Found" error in your NextJs application

I am organizing my files in the following structure src/ ├── app/ │ ├── pages/ │ │ ├── authentication/ │ │ │ ├── SignUp/ │ │ │ │ └── page.tsx │ │ │ └── SignIn/ │ ...

Transferring data from an Angular variable to an Express backend using a POST request

req.body seems to be coming up empty for me. I've tried adding content-type headers as json, but it's not making a difference. Can anyone point me in the right direction? Thank you. UPDATE: Just to clarify, my Angular frontend is successfully hi ...

The import component path in Angular 4/TypeScript is not being recognized, even though it appears to be valid and functional

I'm currently working on building a router component using Angular and TypeScript. Check out my project structure below: https://i.stack.imgur.com/h2Y9k.png Let's delve into the landingPageComponent. From the image, you can see that the path ...

Upon clicking, Vue triggers form validation in Laravel

I have encountered an issue that I am unable to solve by myself: Within my Laravel view, I have included a form in the following manner {!! Form::open(array('route' => ['reports.store', $project->id], 'data-parsley-validate& ...

Having trouble with the width of the Material-UI drawer feature

Encountering an issue with the material-ui drawer. I adjusted the width of the drawer container, which led to a problem where the drawer remains slightly inside the page and visible without clicking the button. It seems to be related to the transform attri ...

Accurate understanding of URL parameters and hashtags

Imagine an HTML document containing two blocks, where the content of only one block can be displayed at a time by toggling between them using menu buttons and/or URL parameters with the same JavaScript functions provided below: <div class="block1&q ...

The method JSON.stringify is not properly converting the entire object to a string

JSON.stringify(this.workout) is not properly stringifying the entire object. The workout variable is an instance of the Workout class, defined as follows: export class Workout { id: string; name: string; exercises: Exercise[]; routine: Ro ...