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

Issue with AngularJs: $http post only posting single item to collection inside a for loop

I have a collection that requires me to post multiple items in a for loop. Below is the code snippet: for(i = 0; i < 28; i++) { var request = $http({ method: "post", url: "/students", ...

Eliminate JSON data that pertains to dates that are either in the past or future

I am working on integrating upcoming classes and past classes components into my application. I have successfully stored the schedule of classes and can retrieve them using backend services. However, I need to display only the upcoming classes in one compo ...

Two sets of buttons, however, one set is carrying out the incorrect function

I am trying to create two button sets that, when clicked, are supposed to angle the text below them at 45 degrees. However, I am facing an issue where both set 1 and set 2 only control the text linked to button 1. I need each button set to control their ...

Change the size of the individual cells within JointJS

I have some code for a jointjs demo that includes basic shapes on a paper. I am looking to adjust the size of the shapes or highlight them when clicked on or when the cursor moves over them. var graph = new joint.dia.Graph; v ...

Finding the Ideal Location for Controllers in an Express.js Project

I'm relatively new to software development and one concept that I find challenging is organizing the directory structure of various projects. As I prepare to embark on an Express project, I prefer keeping controller classes separate from route callbac ...

Struggles with fading in and out

I'm currently working on enhancing a pure CSS rollover with a smooth transition/fade effect, but I'm encountering some difficulties in achieving the desired outcome. The concept involves displaying a new div called "online-hover" when hovering o ...

Strange behavior of dropdown submenu

I've encountered an issue where my child's ul li elements are not behaving as expected, despite following advice from other sources. After days of debugging with no success, I am unable to pinpoint the problem. The image showcases the issue perfe ...

Is there a way to prioritize the table row background color over the cell input elements background color?

After a user selects a table row, the row is assigned the class below: tr.selected { background-color:#FFA76C; } However, if there are input fields in the cells with background colors, they end up overriding the row's background color. (For instance ...

Animated CSS sidemenu (utilized as a filtering panel for a table)

Hi there, I'm having some trouble with CSS Animation. I recently started developing websites and am using Bootstrap 4 along with Animate.css for animations. My goal is to have an icon button expand sideways to reveal a div containing select elements f ...

Retrieve the chosen option from a dropdown menu and transfer it to the submit button in PHP

I have a unique situation where I need to extract and store selected values from two separate drop-down menus generated from arrays. The goal is to pass these selected values in the submit button link. For example, if a user selects "123" for email and "t ...

What is the proper way to utilize CSS animation delays in order to design a collapsible HTML container?

I'm trying to implement responsive CSS animation delay to create an accordion effect when a user clicks on an arrow associated with a table, all without using JavaScript and only utilizing HTML/CSS. Check out the mobile view in action here: https://w ...

Position the image to the right of the dropdown menu in Bootstrap

While working with Bootstrap to create a top navbar on my webpage, I encountered some issues: Once the navbar dropdown is opened, I need to display an option list alongside an image positioned to the right of the list. The image should be the same height ...

How come my flex-box navigation bar is not collapsing as I shrink the browser window size?

I'm currently experimenting with FlexBox to enhance the design of my website, specifically focusing on creating a responsive and collapsible navigation bar for mobile users. I'm encountering issues with the flex commands in the .nbar class not wo ...

Implementing dynamic ID routes in React Router using JSON data

As a beginner in React, I have been working hard to improve my skills every day. However, I am currently facing a challenge with creating dynamic routes using JSON characters (specifically from Dragon Ball Z). Although my routes are set up correctly, I wo ...

The share-modal.js file is throwing an error because it is unable to read properties of null, particularly the 'addEventListener' property, at

I encountered an error that I want to resolve, but it's proving to be quite challenging. Despite extensive searching on Google, I haven't found a solution yet. Uncaught TypeError: Cannot read properties of null (reading 'addEventListener&apo ...

Methods for decoding a JSON object and iterating through its contents

After learning how to encode an object on the server side from this post, I am now interested in decoding it on the client side. Following is what I do on the client side: $.ajax({ type: "GET", url: "/cgi-bin/ajax_sort.pl", contentType: "appl ...

Looking to implement pagination in Vue.js - what steps should I take?

Hi there, I'm currently facing an issue while trying to paginate my data. The error message in my console reads: Property or method "$index" is not defined on the instance but referenced during render. Below is my HTML template where I display the da ...

Cross-Origin Resource Sharing Problem - Angular version 8 with NodeJS and ExpressJS

I've attempted various solutions from different sources and have a feeling that I may be overlooking something minor here. In my setup, I have an AngularJS 8 application running on Node 10 with ExpressJS. The specific issue I'm encountering rela ...

It appears that the size of the textlabel in the HTML is not responsive to

When working with my HTML code, I've encountered an issue where I am unable to modify the height and width of a label using CSS. However, I have found that I am able to adjust the top and left positioning. HTML: <div id="loginname"> <l ...

Having trouble loading select2 using PHP/Ajax/JSON even though I can see the data in the inspector

I encountered a puzzling issue after deploying my web application from a Windows (XAMPP environment) to a Linux Server. Despite everything working perfectly on Windows, I am now facing a frustrating problem that has left me stumped. I have scoured through ...