JavaScript function not functioning properly with variable input

I'm currently working on implementing two functions that will allow me to navigate through an array of image sources and display them in my image view: nextImage() and previousImage(). Everything seems to work fine when I hardcode the num variable, but when I try to make it more dynamic by passing it as a parameter during window.onload, the functionality breaks. It only goes forward to number 1 and doesn't go backwards. Take a look at the code below. Any help would be greatly appreciated! - Alessandro

var num = 0;

var imagesArray1 = ["img/campionatigiovanili2018/img1.jpg", "img/campionatigiovanili2018/img2.jpg", "img/campionatigiovanili2018/img3.jpg"];

window.onload = function(){
  let logo = document.getElementById('logo');
  logo.addEventListener("click", function(){
    window.location.href = "index.html";
  });

  document.getElementById('postImage1').setAttribute("src", imagesArray1[num]);

  //Previous Image
  document.getElementById('previousImage').addEventListener("click", function(){
    previousImage("postImage1", imagesArray1, num);
});

document.getElementById('nextImage').addEventListener("click", function(){
  nextImage("postImage1", imagesArray1, num);
});

};

function nextImage(postImage, imageArray, myVar){
  if (myVar < 2) {
    myVar = myVar + 1;
    document.getElementById(postImage).setAttribute("src", imageArray[myVar]);
    console.log(myVar);
  } else {
  }
};

function previousImage(postImage, imageArray, myVar){
  if (myVar > 0) {
    myVar = myVar - 1;
    document.getElementById(postImage).setAttribute("src", imageArray[myVar]);
    console.log(myVar);
  } else {
  };
}

Answer №1

Ensure you access the num variable within the function, rather than passing it as a parameter:

function displayNextImage(postImage, imageArray){
  if (num < 2) {
    num = num +1
    document.getElementById(postImage).setAttribute("src", imageArray[num]);
    console.log(num);
  } else {
  }
};

Note that myVar and num are distinct variables in this scenario.

Answer №2

In Javascript, parameters are always passed by value if they are primitive types (such as your num variable).

To solve this issue:

  • You can simply edit num directly inside the event handler since it's a global variable.

  • Alternatively, you can declare it as an object like this: var currentObj = { num: 0 };

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

How can I convert XSLT XML to HTML, specifically matching elements that begin with 'n' but exclude those containing 'name'?

Encountered a puzzling issue here. The source XML looks like this: <n0>Hello1</n0> <n1>Hello3</n1> <name>Hello2</name> I have figured out that I can utilize <xsl:template match="*[starts-with(name(),'n' ...

Centered offsetting with Bootstrap 4

I am looking to create a column that is centered on the page, with another column slightly offset from it, without affecting the center alignment. <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="styl ...

Creating a layout similar to Facebook can be achieved by utilizing HTML and CSS, specifically using flexbox to structure

I am looking to create a website layout similar to Facebook, with the following features: A fixed or sticky header and no footer 3 div elements, where div1:div2:div3 = 1:2:1 3 scroll bars to control each div... Scroll-1 and scroll-3 will be inside div-1 a ...

Is there a way to exclude a specific div based on two select choices?

Check out my Fiddle demonstration here $('select#classes').on('change', function() { var selectedClass = $(this).val(); $('.col-sm-6:not(:contains(' + selectedClass + '))').hide(); $('select#subjec ...

The parameters remain consistent across all Angular directives

I have created a directive called 'filterComponent' with the following code: app.directive('filterComponent', function() { return { restrict: 'E', templateUrl: 'filter-component.html', link: function ...

Data connections in React Firebase provide essential links between multiple pieces of information

In my React application, there is an Administration area where the Admin user can add items to a large catalog stored in Firebase under "catalogue". When a regular user logs into their account, they can see the list of items added by the Admin and choose ...

Utilizing CSS for a specific row within the grid-template-areas placement

Hey there, I'm diving into the world of coding and taking on a new project as a beginner. My goal is to recreate Google's Advanced Search page from scratch. Right now, I'm focusing on creating the header section using the power of display: g ...

Next.js - Exceeding Optimal Bundle Size by Approximately 3 Megabytes

Is there a way to decrease the size of my Next.JS bundle, specifically the Node Modules that are causing excessive loading time and slowing down browsing speed? Check out this analysis for more details: https://i.sstatic.net/3LQz4.jpg I'm happy to p ...

Shutting down a React Semantic UI modal using a combination of a button and a close

I've created a Modal where users must fill out forms and save the entered information by clicking a button within the Modal. However, I'm facing an issue - even though I can close the Modal using the open prop on the Modal component, I'm una ...

Mesh does not display texture in three.js

I've been attempting to add a texture to my sphere mesh using the code snippet below: var loader = new THREE.TextureLoader(); var balltex = loader.load("pic1.jpg"); var ballmat = new THREE.MeshBasicMaterial({ map: balltex }); var ballgeo = new THREE ...

When the FileReader reads the file as readAsArrayBuffer, it ensures that the correct encoding is used

Currently, I am developing a script in JavaScript to read uploaded .csv/.xlsx files and convert the data into an array containing each row. Using FileReader along with SheetJs, I have successfully managed to achieve this by implementing the following code: ...

Themed CSS for Header in HTML Tables

Looking to add some creative CSS theming to the header of a table? Unfortunately, tables don't support this natively. But fear not – there's a workaround! My solution is to insert an element BEHIND the table head and apply the desired styles t ...

Displaying a Div Element using jQuery based on a PHP list

After researching how to toggle a div using jQuery based on dropdown selection made with "select" and options, I am facing a challenge. The dropdown selection code I am working with is as follows: <?php echo $this->lists['catid']; ?> T ...

The application experiences crashes when the tablet is rotated, happening while in the development stage

For my web-based Android application project, I am utilizing PhoneGap and Eclipse IDE on a Windows platform. My focus is specifically on Tablet development, more precisely on the Samsung Galaxy Tab 10.1. To develop, I use Eclipse and test the app on the ...

What is the best way to retrieve the value of a selected button from a v-btn-toggle?

<v-btn-toggle v-model="toggle_one"> <v-btn flat> CAD50 </v-btn> <v-btn flat> CAD100 </v-btn> <v-btn flat> CAD1000 </v-btn> <v-btn flat> CAD10000 </v-btn> ...

Picture cramped within a flexbox

I have a div containing an image that is larger than the screen, and I've set the div to be full width with overflow hidden. It works perfectly without creating scrollbars. However, when I try to use flexbox on this div, the image gets squeezed. Inter ...

Tips for enabling autocomplete in ASPX using the original page request exclusively

Currently, our team is working on a project involving an ASPX (.NET 2.0) page with a select list that contains over 200 elements. We are in need of autocomplete functionality to transform this select list into a user-friendly text box with auto-suggestion ...

Looking to improve query performance on MongoDB using mongoskin - should you use a single query or

this relates to mongodb {cod_com:'WWWOAN', cod_prod[{prod:'proda',info:'hello world'},{prod:'pacda',info:'hello world'},{prod:'prcdb',info:'hello world'}] } {cod_com:'WWWOA2&a ...

Creating dynamically generated nested text inputs with individual v-model bindings upon the clicking of a button

As a newcomer to vuejs, I am attempting to create nested textboxes dynamically with the click of a button. For a clearer explanation, please refer to this jsfiddle link: https://jsfiddle.net/avi_02/qLqvbjvx/ Let's use an analogy to grasp the iss ...

Automate Chrome browser to continuously refresh until desired item is located using Selenium and Chromedriver

I am attempting to create a Python script using selenium that will continuously refresh the current Chrome page until a specific item, identified by driver.find_element_by_partial_link_text("Schott"), is found. This is what I had in mind: while not drive ...