Unable to populate an array using JavaScript

I am a newcomer to JS programming and I am eager to create my own script for more practice. However, I could use some assistance. To begin with, I have a basic array set up at the start of my script:

Var    
viewportHeight = $(window).height();
contentTop = [0, viewportHeight, viewportHeight*2, viewportHeight*3, viewportHeight*4];

Then, in the middle of the code, I require a function that will trigger on window resize and update the array with new values.

$(window).resize(function() {
  for (i = 0; i < contentTop.length; i++) {
    contentTop[i] = {
      viewportHeight * i
    };
  }
});

Similar procedures seem to work in other programming languages, but not in JS, at least in my case. Is there an alternative approach to accomplishing this?

Thank you in advance,

Alex

Answer №1

To ensure the accuracy of the viewportHeight variable, make sure to update it whenever the window size changes and eliminate the use of curly braces.

$(window).resize(function() {
   viewportHeight = $(window).height();  // Ensure values are updated correctly
   for (i = 0; i < contentTop.length; i++) {
      contentTop[i] = viewportHeight * i;  // Remove unnecessary curly braces
   }
});

Answer №2

Remove the curly brackets and attempt this method instead - contentTop[i] = viewportHeight * i;

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

Unable to reset input fields in Javascript problem persists

Check out my JSFiddle demo: http://jsfiddle.net/kboucheron/XVq3n/15/ When I try to clear a list of items by clicking on the "Clear" button, I want the text input field to be cleared as well. However, I am unable to achieve this functionality. <input t ...

Optimal Placement of jQuery Event Handlers in React/Redux Components with Asynchronous Data Loading

After reviewing the ReactJS documentation, it's clear that the most suitable lifecycle method for handling redux action calls is componentDidMount. However, I'm facing a challenge when it comes to incorporating jQuery operations within this parti ...

Global Path in Helmet Content Security Policy is not functioning as expected

I recently implemented Helmet to establish content security policies for my web application using Express in the backend. The specific policies are as follows: const express = require("express"); const app = express(); const helmet = require('helmet&a ...

Enhancing functionality by integrating Jquery/JS with input fields and labels

I am currently facing a challenge in applying CSS to the label element when the corresponding input is selected. After attempting and failing to use input:checked + label due to limitations in the HTML structure that cannot be altered, I seek alternative ...

What is the simplest method for generating a datatable?

What is the best way to set up a datatables table? I've tried implementing datatables features like search, pagination, dropdowns, and sorting in my existing table, but it's not functioning properly. Even though I'm using the CDN versions o ...

What is the best approach to dynamically implement useReducer in code?

Take a look at the repository here: https://github.com/charles7771/ugly-code In the 'Options' component, I am facing an issue where I am hardcoding different names for each reducer case instead of dynamically generating them for a form. This app ...

What is the best way to utilize integer pointers in the function parameter to determine the positions of the highest value in a 2-dimensional array and then return the pointer?

double * findLargestElement(double array[][COL], int rows, int* row_index, int* column_index) { double * ptr = 0; double max_value = 0; for (row_index = 0; *row_index <= rows; row_index++) { for (column_index = 0; *column_index &l ...

Tips for continuously randomizing colors in p5.js

I recently began exploring p5.js and I have a query regarding color randomization. Currently, it seems that the color only changes randomly when I restart the code. Is there a way to trigger this randomization every time the mouse is clicked? Below is the ...

Is it Necessary to Wait for my Script Tag in React when Utilizing a CDN?

My current project involves the use of a CDN to load a script, which I am implementing through the useEffect hook directly in my component. Here is the simplified code snippet: React.useEffect(() => { const script = document.createElement('scri ...

Toggle class for a div upon clicking

I am attempting to add a class to a div element when it is clicked. Unfortunately, I'm having trouble getting it to work despite setting it up in the following manner: Javascript: function choose() { this.addClass("selected"); } HTML: <div ...

JavaScript image search function within the existing page

Building a HTML website is new to me and I lack basic programming skills. I've uploaded 100 animated images to another server and linked them to my HTML website using code like this: <p> <img src="http://.../abc/23118465.gif" alt="teddy be ...

Significant Google Maps malfunction detected with API V3

Update: Issue resolved, check out my answer below. The scenario: User interacts with a map-image google maps API V3 is loaded using ajax the map is displayed in a dialog window or lightbox What's going on: The map loads and all features are funct ...

Change the class of <body> when the button is clicked

One of my tasks involves adding a button that, when clicked, should give the body the class "open-menu". Implementing this using jQuery was quite straightforward - I just needed to add the following line of code: $('.burger').click(function() ...

Unable to fetch css file in Node.js

I am currently in the process of learning Node.js, but I have encountered a small issue with retrieving data from a css file. Interestingly, when I directly add the data to the index file's code, it seems to work perfectly. Let me share the relevant ...

Generating Unique Random DIV IDs with JavaScript

Does anyone know of a JavaScript solution to generate unique random DIV IDs? I am currently using PHP for this purpose. <?php function getRandomWord($len = 10) { $word = array_merge(range('a', 'z'), range('A', &apos ...

Using Javascript to implement a Validator Callout Control for a specific section of the page, not the entire

Is there a way to configure the validation validator controls to only trigger validation for specific sections of the page? For instance, if we have an accordion, I would like validation to be applied only to one section at a time, rather than all validato ...

Creating individual components for <select> and <option> elements in ReactJS

I am uncertain about how references function when the select and option tags are used together. When I split them into separate React components, they stop working. How can I resolve this issue? Here is a basic example: <select> {() => ( ...

Dealing with special characters in a json XMLHttpRequest: A guide

I'm currently grappling with the best approach for handling special or foreign characters within an AJAX request. My current test code is as follows: var xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST","test.json",true); xmlhttp.setRequestHeader ...

Having trouble with the javascript dropdown functionality

I am currently facing an issue with my Javascript menu. The hover and click functionality for the main menu items is working perfectly fine, but I am struggling to make the dropdown feature work. Here is the code snippet from menu.js: /* When the user cl ...

The middleware function in my express server is not being identified

Currently, I am tackling server-side rendering in React and have developed a basic server in Express. However, I'm encountering the "TypeError('app.use() requires a middleware function')" error repeatedly. Below is a snippet of my app.js: v ...