Adding an unspecified CSS attribute to an element within a JavaScript array

How can I apply a CSS property to only the second element in this array?

I have defined a global variable for the array like this:

<canvas id="canvas"></canvas>
<script>
    var paddles = [2], // Array containing two paddles
function update() {
    // Update scores

    updateScore(); 
    // Move the paddles on mouse move
    // Here we will add another condition to move the upper paddle in Y-Axis
    if(mouse.x && mouse.y) {
        for(var i = 1; i < paddles.length; i++) {

        p = paddles[i];

        // the botoom paddle
        if (i ==1){
            p.x = mouse.x - p.w/2;
        }else{
        // the top paddle
                    //paddles[2].x = mouse.x - p.w/2;
                    debugger
                 paddles[2].style.backgroundColor="red"; 

    }



        }       
    }

I want to apply the following style to the second element:

paddles[2].style.backgroundColor="red"; 

However, when using the debugger, I encounter the following error:

TypeError: paddles[2].style is undefined

Answer №1

UPDATE:

It seems that you are working on a "pong" or "breakout" game, so I decided to try my hand at creating an HTML canvas version for fun. Here's a simple implementation that demonstrates:

  1. Drawing two paddles on a canvas (original author)
  2. Keeping track of the paddle 'boxes' in an array (original author)
  3. Using a loop with setInterval to redraw the canvas as updates are made (original author)
  4. Allowing keyboard input to move shapes around on the HTML canvas (my contribution)

Check out the fiddle for a working demo and the full code: http://jsfiddle.net/z4ckpcLc/1/

I'm not sharing the complete code because most of it isn't mine. I borrowed the box drawing and tracking from this site:

The new function I added is the arrowKeyMove() handler, connected to the onkeydown event of document.body like so:

document.body.onkeydown = arrowKeyMove;

function arrowKeyMove(e) {
    var direction = 0; // -1 for left, 1 for right, 0 for no movement
    var moveFactor = 10; // higher factor means more movement when arrow keys are pressed
    var arrowKeyUsed = false; // indicates which paddle is being moved
    switch (e.which) {
        case 37:
            // left arrow (upper paddle)
            direction = -1;
            arrowKeyUsed = true;
            break;
        case 39:
            // right arrow (upper paddle)
            direction = 1;
            arrowKeyUsed = true;
            break;
        case 65:
            // Key "a" for left strafe (lower paddle)
            direction = -1;
            break;
        case 68: 
            // Key "d" for right strafe (lower paddle)
            direction = 1;
            break;
    }
    var boxIndex = 1; // default to lower paddle
    if (arrowKeyUsed) { // moving upper paddle with arrow keys
        boxIndex = 0; 
    }
    var maxX = 240; // constrain movement within 10px of box borders (240 == canvas width minus paddle width minus padding)
    var minX = 20;
    var box = boxes[boxIndex]; // get the box to update position and redraw canvas
    if((direction < 0 && box.x >= minX) || (direction > 0 && box.x <= maxX))
    {
      // move the box in the desired direction multiplied by moveFactor
      box.x = box.x + (direction * moveFactor);
      invalidate(); // canvas needs redrawing since graphics changed
    }
}

ORIGINAL ANSWER:

Arrays use zero-based indexing.

If you have only two paddles, then you should use index 1, not 2. To access the first paddle, use 0, not 1. Adjust your for loop accordingly by changing instances of checking for 1 to 0.

For example:

paddles[0].style.backgroundColor="red";  // adjusting for paddle 1
paddles[1].style.backgroundColor="red";  // adjusting for paddle 2

Also, var array = [2] does not create an array with two elements. It creates an array with one element having an integer value of 2

When dealing with DOM elements, consider something like this:

<div id='paddle1'></div>
<div id='paddle2'></div>

<script type='text/javascript'>
var paddles = [];
paddles[0] = document.getElementById('paddle1');
paddles[1] = document.getElementById('paddle2');
paddles[0].style.backgroundColor="red";  // setting paddle 1 color to red
paddles[1].style.backgroundColor="orange";  // setting paddle 2 color to orange
</script>

Answer №2

I am unsure, but perhaps a solution similar to the following could be helpful:

paddles[2].style.backgroundColor = 'red'; 

Update: I just realized you are not utilizing jQuery, so my previous suggestion may not be applicable

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

Having trouble with JavaScript's variable scoping?

Currently, I am using Node.js and mongoose, but I have encountered a challenging issue: var dbvar; doc_model .findOne({aadhar}) .then(()=>{ dbvar=1; }); paramedic_model .findOne({aadhar}) .then(()=>{ dbvar=2; }); console.log(dbva ...

Troubles with submitting jQuery validation plugin via AJAX

Whenever I try to use the jQuery validation plugin for validating a form within a Bootstrap modal, the validation does not work and the form cannot be submitted. This is the code for the Bootstrap modal form: <div class="modal fade" id="form-content" ...

Analyzing Array Data with PHP

I am looking to analyze JSON data with a comparison in mind. Here is the code snippet I have written for this purpose: $packages[0][0] = "5678"; // en route $packages[0][1] = "3098"; // at checkpoint $packages[0][2] = "4331"; // accepted if (array_key_ex ...

Exploring the possibilities with Three.js and MVC architecture

I have developed a basic 'hero creation' program in three.js, inspired by Elder Scrolls where users can swap through different heads, bodies, etc. to create a full character. I am interested in making this program more interactive by allowing mul ...

Scrolling triggers the click event

Within my JavaScript code, I have a rather simple event listener set up to listen for a click: element.addeventlistener('click', ()=>{ #do somthing }) However, I am encountering an issue on IOS (iPhone) where scrolling triggers the event list ...

`Is there a way to retrieve data from an array of Input elements using PHP?`

I am currently working on implementing a contact form using J Query, PHP AJAX. In the code snippet below, I am gathering form information and sending it to the server using a for loop and an array of form inputs. As someone who is new to this type of co ...

How can I dynamically adjust the stroke length of an SVG circle using code?

In my design project, I utilized Inkscape to create a circle. With the fill turned off, only the stroke was visible. The starting point was set at 45 degrees and the ending point at 315 degrees. After rotating it 90 degrees, here is the final outcome. < ...

Issue with resizing a Bootstrap pill containing truncated text

After struggling with this issue for some time, I attempted to use javascript to solve it but have been unsuccessful. The challenge involves a tag list in a table that displays a link when hovered over. Following advice from another member on SO, I managed ...

How can I resolve the issue of neglecting the result of `inputstream.read` in IntelliJ?

Currently, I am in the process of resolving potential bugs within my application. To evaluate my code, I have decided to utilize Sonar. However, I have encountered an issue that has left me puzzled: private Cipher readKey(InputStream re) throws Exception ...

bash array > iterate over loop up to x elements

Currently, my script includes a for loop that looks like this: for server in "${servers[@]}"; do if nc -v -z -w1 ${server} 3389 2>/dev/null; then xfreerdp /u:$username /p:$pass /t:"$1""-""${server}" /w:$width /h:$height +cert-ignore +wm-class:xfre ...

What is the best way to extract the image url from a page in WordPress?

Is there a way to extract the image URL in WordPress dynamically for use as a reference in a script? When I use postimage(); it extracts this: <a href="address"> <img width="300" height="300" src="image.png" class="image" alt="" title="LINKING"/& ...

Extraction of properties from an object in an ES6 class

How should object destructuring be properly applied for methods within ES6 classes? user.ts import { Request, Response } from "express"; export class User { constructor (){ Object.assign(this,{ root:this.root, get:this.get ...

Chrome's React does not maintain the desired scroll position when adding new DOM items

Encountered an interesting issue while trying to add new items to a state array in React. This resulted in more items being added to the DOM, but the way they appeared varied across different browsers. Safari and Firefox placed the new items below the fold ...

Ways to determine if a date is inactive in the Bootstrap Datepicker interface

I need assistance with my form that contains three <input> elements. <input id="from-date" type="text" class="form-control" placeholder="From"> <input id="to-date" type="text" class="form-control" placeholder="To"> <input id="total" c ...

Exporting multiple HighCharts visualizations to PowerPoint presentations

Our team is preparing to create an Angular-based web application featuring 15-20 unique charts utilizing HighCharts. One of the key requirements is the ability to export these charts into PowerPoint slides. We are aware that HighCharts offers an option to ...

How can I convert a PHP date to a JavaScript date that works across all

I am attempting to create a JavaScript countdown timer that relies on the server time, but I'm facing difficulties in transferring PHP time to JavaScript seamlessly across different browsers. While it functions correctly in modern browsers, older ones ...

Determine the maximum size of a specified number of square divs that can fit within responsive parent divs

I am working on creating a grid of square divs inside a container with variable height and width. The number of square div's is predetermined. All square divs will have images with the same dimensions (similar to the example). They should align left ...

Responding with a 404 Error in Node.js and Express with Callbacks

Apologies for the lackluster title, I couldn't come up with anything better. Let's delve into the following code snippet: app.use(function(request, response){ request.addListener('end', function() { parseUrl(request.url, fu ...

Tips for uploading images in Next.js using Firebase

While following a tutorial on Next.js, I encountered an issue with the outdated version of Firebase being used. Despite trying different solutions from the documentation and various sources, I am still facing an error message while attempting to upload ima ...

Tips for triggering a function when the range slider is adjusted

I'm looking to trigger a function whenever a user changes a range slider in my Vue.js project, and I also need to pass the new value to that function. The code snippet below shows what I have so far. <div cla ...