Unable to specify the element within the array

I'm having trouble getting my array elements defined. When I try to alert them, I always receive NaN. Even though the jQuery selectors seem to be working perfectly. Can someone help me figure out what the problem might be?

        var sldr                                = $("#slider img"),
            count                           = sldr.length-1,
            containerHeight         = $("#slider").css('height'),
            images                          = new Array(),
            imgHeights                  = new Array(),
            imgWidths                       = new Array(),
            imgSlices                       = new Array(),
            choosenSlice                =   '',
            slicer                          = '';


        var i=0;
        for (i=0;i<=count;i++){
            images[i]               = $("#slider img:eq("+i+")");
            imgHeights[i]       = $("#slider img:eq("+i+")").attr('height');
            imgWidths[i]        = $("#slider img:eq("+i")").attr('width');
            imgSlices[i]        = (Math.round(imgHeights[i]/containerHeight))-1;
            alert(imgSlices[i]);
        }

Answer №1

If the height or width attribute is missing from one of the images, or if it's not a valid number, attempting to divide by it could lead to a NaN result.

To avoid this issue, you can convert those values to numbers using the parseInt function:

imageHeights[i]       = parseInt($("#gallery img:eq("+i+")").attr('height'));
imageWidths[i]       = parseInt($("#gallery img:eq("+i")").attr('width'));

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

Create an object with an asynchronous function/promise declaration

I have a function that returns an object with different functions that I can use. I want to incorporate promises into these functions for better asynchronous handling. var DATABASE = (function () { var exports = {}; exports.query = function(filter = ...

What is the best way to showcase the outcomes of arithmetic calculations on my calculator?

In the midst of creating a calculator, I have encountered some issues in getting it to display the correct result. Despite successfully storing the numbers clicked into separate variables, I am struggling with showing the accurate calculation outcome. l ...

Is it possible to pass multiple API props to a NextJs Page at once?

I am currently facing a challenge in rendering a page that requires data from two different API fetches. The URL in the address bar appears as: http://localhost:3000/startpage?id=1 Below is the code snippet for the first API fetch: import { useRouter } f ...

The distinction between using document.getElementById and document.getElementsByClassName in JavaScript

One thing that stands out is why does document.getElementsById function as expected here <div id="move">add padding</div> <button type="button" onclick="movefun()">pad</button> <script> function movefun() { document.get ...

Material-UI rating component outputs a string instead of a numerical value

I'm encountering an issue with the Material UI rating component. Despite providing it with a number as the initial value (this.props.data.feelings_rating), it returns a string whenever I change it within my app. Below is the relevant code: Rating co ...

The time update in React Js is not showing on Material UI's DatePicker

Utilizing the Material UI KeyboardDatePicker in my application has proven to be quite tricky. When I select a date, the initial selection displays both the date and time correctly. However, after waiting for 1-2 minutes and selecting another date, the date ...

Tips for designing a Quasar page that dynamically loads content as the user scrolls

I am attempting to develop a component that will render multiple elements as the page is scrolled. I am utilizing the Quasar framework for Vue.js. Below is the code required to render a single block containing information from a JSON file: Quasar comes wi ...

Finding the sub-array within the main array that is shifted one position to the right

I have a large numpy array called a=[55,12,12....] . My goal is to create sub-arrays of size 300 starting from index 55 in the array a, then shift one position to the right from index 12 to obtain a new sub-array. This process needs to be repeated until th ...

What methods can be used to ensure that the variable $ can serve as both an object and a function?

One interesting feature of jQuery is how the variable $ can function as both an object and a function. // For example, you can access object properties like $.fn; // or $.isReady; // You can also call the function $ like this $(); So, how can we make the ...

Is there a way to return two separate functions within a single function that can be rendered as two distinct components in a React application without one function overriding the other?

I'm currently working on a react header that uses conditional rendering to show different elements based on the URL or user login status. However, I'm facing an issue where only one button is being rendered instead of two side by side in my defau ...

Artboard: Easily navigate through pictures

As part of a school assignment, I wanted to create an interactive story where users can click through images using the UP and DOWN buttons. However, I am facing an issue with my If function overriding the previous function. I envision this project to be a ...

Which specific HTML element triggers the initiation of ajax in Jquery?

I have a situation where various HTML elements trigger ajax requests when clicked. My goal is to determine which specific element was clicked inside the ajaxComplete event. Although I attempted to use event.target, it only returns the entire document inst ...

The input data from the MySQL database requires two page refreshes in order to be retrieved

Every time I input new values into the form fields and submit them, the page needs to be reloaded twice to display the updated values. For example, consider the $balance_2 in the 7th line. This line calculates the sum of all row values and updates the Bal ...

The jQuery function does not accurately represent the class change made by another event

When hovering over a class anchor, an alert will display the title value. If the anchor has a nohover class, a nopop class will be added to prevent the alert. This ensures that the alert only appears when hovering over the class anchor without the nopop cl ...

Is there a way to modify the color scheme of my webpage while utilizing Bootstrap?

As I delve into programming with Bootstrap, I encountered an issue while attempting to change the background color of my body. Even though I used the following CSS code: body { background-color: #eba; width: 100%; height: 100%; } The color change ...

I am having trouble getting Form.Select to work in my basic react-bootstrap application, despite following the guidelines provided in the react-bootstrap documentation. Can

I am new to utilizing "react-bootstrap with hooks" and currently in the process of creating a basic form. I have been following the guidance provided by react-bootstrap documentation, but I encountered an issue specifically with select/option form elements ...

Monitor the DOM for visibility changes in Selenium WebDriver and PjantomJS before proceeding

I am currently creating automated test scripts using selenium-webdriver, phantomJS, and mocha. The script file I'm working with is a JavaScript file. My goal is to wait until an element (<a>) is fully visible before clicking on it. Let me pro ...

Steps for retrieving user timezone offset and transmitting it to the server in an ASP.net application

I need assistance with capturing and sending a user's timezone or offset when they successfully sign in. I came across the "getTimezoneOffset" method in JavaScript, but I'm unsure how to automatically send this data without the user explicitly in ...

My JavaScript/jQuery code isn't functioning properly - is there a restriction on the number of api calls that can be made on

Below is the code I have implemented from jquery ui tabs: <script> $(function(){ // Tabs $('#tabs1').tabs(); $('#tabs2').tabs(); $('#tabs3').tabs(); //hover states on the sta ...

Getting the first array from a fetch promise is a process that involves accessing the

When working with a fetch promise, I need to return a JSON object that contains all of my data. The challenge is that I am not sure what the object name will be. What I do know is that there will always be one object present. Below is an example of my cod ...