How to retrieve the index upon clicking in Javascript

In my 3d art gallery project, I am utilizing plain JavaScript. The task at hand involves populating certain columns with images by pulling from an array of image sources. On click, I need to retrieve the index of the clicked image so that I can extract additional information such as titles and descriptions from the array.

While I could easily achieve this using jQuery, I am committed to learning plain JavaScript. All images already have event listeners in place. Below is the current code snippet:

var preview = document.getElementById('preview');
var subwrap = document.getElementById('subwrap');
var indexMatch;

for (var i=0; i <= imgList.length; i++){

    document.images[i].addEventListener("click", srcSend, false);

}

function srcSend(){

    var previewTitle = "Test Title";
    var previewText = "Test Description";
    var imgSrc = this.src;

    console.log('Image Source ='+''+imgSrc+'');

    if (imgSrc !== "file:///D:/Projects/mpaccione/img/navicon.png"){

    preview.className = " ";
    subwrap.className = "hide";
    preview.className = "show";
    preview.innerHTML = '<img src='+imgSrc+'><p id="title">'+previewTitle+'</p><p id="description">'+previewText+'</p>';   }}

Answer №1

One way to access the Array.indexOf method is by using it in the images collection.

function findIndex(){

    var imageIndex = Array.prototype.indexOf.call(document.images, this);
    
}

Answer №2

If you want to pass the index to the srcSend function, you can follow this example:

for (var j=0; j <= imageList.length; j++){
    document.images[j].addEventListener("click", function(){
        return (function(index) {
            sendDataToSource(index);
        })(j);
    }, false);
}

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

In search of javascript implementations of the pubhubsubbub protocol that are open source

Can you list out some of the open-source Javascript implementations for the PubSubHubbub protocol, starting with the publishing side? ...

Unlocking the full potential of parsing messages using google protobuf-js

Currently, I am developing a front-end application using Angular5+ that utilizes google-protobuf JS and WebSocket for backend communication. Within my .proto files, I have defined 2 objects: a Request object. a Notification object. I have created a han ...

Creating an animated transition for an element's height with CSS

I need to animate the height of a div that doesn't have a specified height. Using max-height isn't an option due to multiple potential height amounts. I attempted adding transition: height 0.2s ease to the div, but it didn't work as expecte ...

What is the best method for communicating between windows in an electron application?

As I embark on the journey of creating my first electron app, I kindly ask for your understanding :) Upon clicking a button in the main Window, a new window should open displaying a JSON string. This action is captured by ipcMain: ipcMain.on("JSON:ShowPa ...

Discovering the earliest and latest dates within an array of date strings

My data consists of an array filled with objects like this data = [ { mas_name: (...), mas_plan_end: (...) // 'YYYY-MM-DD' eg: '2021-03-19' mas_plan_start: (...) // 'YYYY-MM-DD' eg: '2021-03-19' ... }, { ...

Having trouble converting a JSON array into a JavaScript array upon creation

I have encountered this question multiple times before and despite trying various solutions, I have not been able to find success. Summary: My goal is to retrieve the array from the classes.json file and then assign the data in the variable classes from d ...

Using React to organize content within a material-ui layout efficiently

Currently, I am developing a React page using material-ui integrated within Electron. The main requirement is to have an AppBar containing Toolbar and Drawer components. To achieve this, I have referred to the source code from https://material-ui.com/demo ...

Mastering MongoDB update functions in JavaScript

I've encountered some difficulties while using the MongoDB API to update a document. Despite trying various methods, none of them have been successful so far. Strangely enough, inserting and deleting documents work perfectly fine. Let me explain what ...

Best practices for declaring variables in ReactJS

I need help understanding how to declare a variable in a React JS class so that it is accessible in different functions. Here is my code snippet: class MyContainer extends Component { constructor(props) { super(props); this.testVariable ...

Efficient method for retrieving the values of each cell in a row within an array

I've got a standard table here - 6 columns, multiple rows, all filled with data. Right now, my goal is to collect all this table data into an array: tableData(0) = "1, Hans, Testperson, Munich, Germany" tableData(1) = "2, Petra, Tes ...

State variable in Redux is not defined

While there have been numerous similar inquiries on this platform, I haven't been able to find a solution to my particular issue. Below is the React component in question: class MyTransitPage extends Component { componentDidMount() { this.pro ...

How can I obtain the coordinates when the mouse enters Vue?

Trying to create an animation triggered by the mouseenter event in Vue, I ran into a roadblock - obtaining the coordinates of the sections. <script setup> function fetchCoordinates(e) { const coords = { x: e.clientX, y: e.clientY } // This seems to ...

The type 'Argument of (props: ITableProps) => JSX.Element' cannot be assigned to the parameter type of... - React High Order Component

One of the tools I have in my arsenal is a loader HOC This is how the HOC looks like: const withLoader = <P extends object>(WrappedComponent: new () => React.Component<P, any>, loading: boolean) => { return class WithLoading extends ...

How to Generate Custom Expiry Tokens with Firebase Authentication

Currently utilizing Firebase 3.4.1 for my web application. The default token expiry length is sufficient to keep users logged in, but I am interested in managing the expiry manually. Ideally, I would like the token to expire at the end of each session by ...

Executing a query with a `has many` relationship in MongoDB: Step-by-step guide

In my setup with Node, Express, and backbone, I am successfully retrieving records from MongoDB collections using simple queries. However, I am struggling to understand how to query more complex data, such as the one below: db.employees.aggregate( [ ...

Is it possible to trigger a JavaScript function by manipulating the URL of an HTML page?

Imagine this scenario: You have an HTML page located at example.com/test.html that contains several pre-defined JavaScript functions, including one named play(). How can I add JavaScript to the URL in order to automatically trigger the play() function wh ...

Simulating server-side interactions in Node.js with TestCafe

I am currently working on a project where I need to figure out how to mock server-side requests. While I have successfully managed to mock client-side requests using request hooks, I am facing challenges when it comes to intercepting server-side requests ...

"TypeScript function returning a boolean value upon completion of a resolved promise

When working on a promise that returns a boolean in TypeScript, I encountered an error message that says: A 'get' accessor must return a value. The code snippet causing the issue is as follows: get tokenValid(): boolean { // Check if curre ...

Refresh Vue/Nuxt Components Fully

Understanding how this.$forceUpdate() functions, I am not simply looking to re-render the component. In Nuxt applications, page components have asyncData() as a lifecycle method that runs before created(). I utilize this method to retrieve initial data an ...

Should Errors be Handled in the Service Layer or the Controller in the MVC Model?

Currently, I am in the process of developing a Backend using Express and following the MVC Model. However, I am uncertain about where to handle errors effectively. I have integrated express-async-errors and http-errors, allowing me to throw Errors anywher ...