What method can be used to enable an image in an array to redirect to a specific URL when it is clicked?

Suppose I have the following HTML:

 <div>
 <input type="image" id = "mainImg> <br />
 </div>

 <div>
 <input type="image" class = Button src = "buttonImg.jpg" onclick="showImage()">
 </div>

And my JavaScript code is:

var imgArray = new Array ();
imgArray[0] = "image1.jpg"
imgArray[1] = "image2.jpg"
imgArray[2] = "image3.jpg"
imgArray[3] = "image4.jpg"
imgArray[4] = "image5.jpg"

var linkArray = new Array ();
linkArray[0] = "https://link1.com"
linkArray[1] = "https://link2.com"
linkArray[2] = "https://link3.com"
linkArray[3] = "https://link4.com"
linkArray[4] = "https://link5.com"

function diceCast(){return Math.floor(Math.random()*5);};

function showImage(){
    
    var imgNum = diceCast();
    var objImg = document.getElementById("mainImg");
    objImg.src = imgArray[imgNum];

}

I would like to achieve the following:

When the user clicks on 'imgArray[0]', a new page (e.g. _blank) should load with the content from 'linkArray[0]'.

Should I assign 'imgArray[imgNum] = linkArray[linkNum]' for this to work? If so, how can I implement it?

Feel free to provide suggestions on how to make this process more streamlined and user-friendly!

Answer №1

To update the showImage function, modify the onclick property as shown below.

function showImage(){
    var imgNumber = rollDice();
    var imageElement = document.getElementById("mainImg");
    imageElement.src = imageArray[imgNumber];
    imageElement.onclick = ()=>window.open(linkArray[imgNum], '_blank');
}

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

What is the best method to prevent loading on axios.interceptors.request in an ionic vue interceptor?

I have been following a helpful tutorial and implementing the code from it. The tutorial can be found at the link below: Within the tutorial, there is a function being called that triggers on every axios request. Here is the code snippet for reference: mo ...

Exploring JSON Object Iteration Using jQuery for AJAX Requests in JavaScript

I am struggling to grasp this concept. Currently, I have a JSON file that contains a collection of hospitals, including their addresses, operating hours, and phone numbers. My goal is to make an AJAX call to retrieve data from the JSON file and display i ...

Troubleshooting LocalReport Render Errors When Loading Photos Taken with Nikon Coolpix 5600

My RDLC has an embedded image from a Nikon Coolpix 5600 that is causing an error when I call the Render function. Example image: (Page Not Found) Does anyone know what's wrong with this image? The Error: [ArgumentOutOfRangeException: Non-nega ...

Is it possible in Vue.js to create a reactive functionality for a button using a watcher for "v-if" condition?

I have a userlist page with various profiles, including my own. A button is supposed to appear only when viewing my own profile. The issue arises when switching from a different profile to my own (changing the router parameter) - the button should show up ...

Navigating with nodeJS

Currently, I am in the process of learning how to create a Node.js project. My latest endeavor involved following a tutorial to develop a chat application. However, it seems like there is an issue with the routing between the server side and client side. ...

Traversing a nested array using jQuery

I'm attempting to utilize jQuery's each function in order to iterate through the provided array. My aim is to identify the key ("Name") and display its corresponding array values on the webpage. Array ( [E-mail] => Array ( ...

The Nodejs code snippet successfully allows adding items to the cart, however, a problem arises when adding multiple quantities of similar items individually

Cart functionality is working for initially adding new items, but then each item's quantity is added individually from other similar items? // Logic for handling cart addition // router.post("/", verifyToken, async (req, res) => { let o ...

Ensure that scripts with the type of "module" are completed before proceeding to execute the following script

In my HTML document, I have two script tags with type="module" at the bottom of the body tag. Following those, there is another script tag with embedded code that relies on the results of the first two scripts. Is there a method to ensure that this code ...

Can you explain the meaning behind the exclamation mark in Angular syntax?

I've noticed this popping up in a few spots lately, but I haven't been able to find any information about it. I'm intrigued by the use of the '!' symbol in Angular syntax. Can anyone explain what it does? https://i.sstatic.net/sj ...

locating the truth value of the data in an array retrieved from MongoDB

When returning from the mongoose find() function, I need to ensure that is_reqestor = true is checked. However, when updating the document, I pass the id which needs to be updated. let filter = { is_reqestor: true } if (!is ...

How can CORS be activated? Is it through the server or Javascript, and where does this

Currently, I am testing my ReactJS website on localhost:3333 and my ASP.NET Web API 2 on localhost:54690. I am utilizing axios for my AJAX requests, but encountering an error when making a request. XMLHttpRequest cannot load http://localhost:54690/api/ ...

The shopping cart is unable to display the name property as it is undefined

I'm currently working on creating a basic shopping cart using JavaScript. $('.addToCart').click(function(event) { event.preventDefault(); var name = $(this).data('name'); var price = Number($(this).data('price')); ...

Creating a boundary: A step-by-step guide

There is an element that I need help with <div id="square"></div> This element has the ability to move around the document var square = document.getElementById("square"); document.body.onkeydown = function(e) { if (e.keyCode == 37) { ...

The feature of scrolling to a specific element within a bootstrap modal is not functioning as expected

I recently encountered an issue while using a Bootstrap modal. The problem arose when I tried to scroll to a specific element within the modal, but my code didn't produce the desired results. $('#centralModalLg').on('show.bs.modal&apo ...

Exploring Namespaces in JavaScript: A Detailed Example and Syntax Breakdown

Example and explanation of JavaScript namespaces tree. The following namespaces need to be defined in JavaScript: root root.person root.home root.home.relative My attempt that was incorrect: var root=''; root.person=''; roo ...

Is it possible to remove or delete a module in AngularJS?

Is there a way to clear the memory of a previous module in my app that I won't be using after routing to a different location? For instance, let's say my main Angular module is "WebApp" which has dependencies on modules like "catalogApp", "Payme ...

Converting data types when transferring a JavaScript variable to a PHP variable

I have a boolean value stored in a JavaScript variable var value=true; alert(typeof(value)); //Output: boolean I need to pass this variable to a PHP file through AJAX $.ajax({ type: 'POST', data: {value:value}, url: 'ajax.php& ...

A guide on exposing TypeScript classes globally through a WebPack bundle in JavaScript

Currently delving into TypeScript, my aim is to gradually replace JS with TS. However, due to having numerous JS files, my strategy involves creating new classes in TS and incorporating them into my existing JS files for the time being. Eventually, I plan ...

Navigating the way: Directing all TypeScript transpiled files to the build folder

I am currently working on a project using Angular2/Typescript, and I have the tsconfig.js file below: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "target": "es5", "sourceMap": true, ...

Displaying 'Echo' HTML content from a string in an AngularJS application, especially when the string is within a template

While using ionic tinder cards, I need to ensure that each new card is added to a predefined array as an object in the following format: {text: "some_text"} The challenge arises when there is HTML content within the string, and I aim for that HTML to be ...