What is the best way to link text to an image using JavaScript?

I have a query that I need some assistance with. I've developed a random image generator which is working fine so far:

var randPics = document.querySelector("#randPics");
var getPics = document.querySelector(".getPics");


getPics.addEventListener("click", function(){ 
//array to store images for the random image generator
var picsGallery = new Array();
    picsGallery = ["https://static2.jetpens.com/images/a/000/026/26648.jpg?mark64=aHR0cDovL3d3dy5qZXRwZW5zLmNvbS9pbWFnZXMvYXNzZXRzL3dhdGVybWFyay5wbmc&markalign64=dG9wLHJpZ2h0&markscale=19&s=938428f6eca690069a86f66d0754444b",
"http://assets.sajiansedap.com/media/article_image/cover/large/25505-cara-memilih-nanas-yang-matang.jpg",
 "https://cdn.shopify.com/s/files/1/1030/8703/products/epal-hijau-green-apple-each-sebiji_1024x1024.jpg?v=1487817043"]
 
 //generate random no to select the random images
var rnd = Math.floor(Math.random() * picsGallery.length);
//change the pics locations of the source
  randPics.src=picsGallery[rnd]
  });
#randPics{
width: 300px;
height: 300px;
align-content: center;
}
<body>
<p>Display a random image each time the buttons is clicked!</p>
<p> You get a <span id="text"></span>  </p>

<button class="getPics"> Click ! </button>
<br>
<img id="randPics" src="https://d30y9cdsu7xlg0.cloudfront.net/png/45447-200.png">

</body>

Upon clicking the button, a random image from the array will be displayed. However, I am facing an issue with associating text with the images. For example, when the user clicks the button and gets an image of a pen, the text should change to:

You get a

should change to

You get a pen.

Your insights would be greatly appreciated!

Answer №1

To begin, it is essential to store the text in a designated location and then establish a connection between the text and images. One way to achieve this is by storing the text along with corresponding images in an object array instead of solely having an array of image URLs. Additionally, there is no need to declare the array within the event handler function; it can be defined once and accessed within the function since it resides in the scope. Here's an example:

var randPics = document.querySelector("#randPics");
var getPics = document.querySelector(".getPics");
var textElem = document.querySelector("#text");

//array for storing images for random image generation
var picsGallery = [{img: "https://static2.jetpens.com/images/a/000/026/26648.jpg?mark64=aHR0cDovL3d3dy5qZXRwZW5zLmNvbS9pbWFnZXMvYXNzZXRzL3dhdGVybWFyay5wbmc&markalign64=dG9wLHJpZ2h0&markscale=19&s=938428f6eca690069a86f66d0754444b", text:'pen'},
{img: "http://assets.sajiansedap.com/media/article_image/cover/large/25505-cara-memilih-nanas-yang-matang.jpg", text:'pineapple'},
 {img: "https://cdn.shopify.com/s/files/1/1030/8703/products/epal-hijau-green-apple-each-sebiji_1024x1024.jpg?v=1487817043", text:'apple'}];

getPics.addEventListener("click", function(){ 
   
 //generate random number to select a random image
var rnd = Math.floor(Math.random() * picsGallery.length);
//change the source of the displayed image
  randPics.src=picsGallery[rnd].img;
  text.innerHTML = picsGallery[rnd].text;
  });
#randPics{
width: 300px;
height: 300px;
align-content: center;
}
<body>
<p>Display a random image each time the button is clicked!</p>
<p> You get a <span id="text"></span>  </p>

<button class="getPics"> Click ! </button>
<br>
<img id="randPics" src="https://d30y9cdsu7xlg0.cloudfront.net/png/45447-200.png">

</body>

Answer №2

Declare the array picsGallery outside of the event handler.

Create an array with two elements for each element in the picsGallery array. Assign the value of picsGallery[rnd][0] to .src of <img>, and picsGallery[rnd][1] to the .textContent of #text

var randPics = document.querySelector("#randPics");
var getPics = document.querySelector(".getPics");
var text = document.querySelector("#text");

var picsGallery = [
  ["https://static2.jetpens.com/images/a/000/026/26648.jpg?mark64=aHR0cDovL3d3dy5qZXRwZW5zLmNvbS9pbWFnZXMvYXNzZXRzL3dhdGVybWFyay5wbmc&markalign64=dG9wLHJpZ2h0&markscale=19&s=938428f6eca690069a86f66d0754444b", "pen"],
  ["http://assets.sajiansedap.com/media/article_image/cover/large/25505-cara-memilih-nanas-yang-matang.jpg", "pineapple"],
  ["https://cdn.shopify.com/s/files/1/1030/8703/products/epal-hijau-green-apple-each-sebiji_1024x1024.jpg?v=1487817043", "apple"]
];

getPics.addEventListener("click", function() {
  var rnd = Math.floor(Math.random() * picsGallery.length);
  //change the pics locations of the source
  randPics.src = picsGallery[rnd][0];
  text.textContent = picsGallery[rnd][1];
});
#randPics {
  width: 300px;
  height: 300px;
  align-content: center;
}
<body>
  <p>Display a random image each time the buttons is clicked!</p>
  <p> You get a <span id="text"></span> </p>

  <button class="getPics"> Click ! </button>
  <br>
  <img id="randPics" src="https://d30y9cdsu7xlg0.cloudfront.net/png/45447-200.png">

</body>

Answer №3

I have made some adjustments to your code by linking all images with text and organizing them within a JavaScript object instead of an array. Other than that, the code remains mostly the same as what you originally wrote.

<!DOCTYPE html>
<html>
<head>
  <title></title>
<style type="text/css">

    #randPics{
      width: 300px;
      height: 300px;
      align-content: center;
    }

</style>
</head>
<body>
    <body>
    <p>Display a random image each time the buttons is clicked!</p>
    <p> You get a <span id="text"></span>  </p>

    <button class="getPics"> Click ! </button>
    <br>
    <img id="randPics" src="https://d30y9cdsu7xlg0.cloudfront.net/png/45447-200.png">

<script>
    var randPics = document.querySelector("#randPics");
    var getPics = document.querySelector(".getPics");


    getPics.addEventListener("click", function(){ 
    //object to store images for the random image generator
    var picsGallery =  {"bar": "https://static2.jetpens.com/images/a/000/026/26648.jpg?mark64=aHR0cDovL3d3dy5qZXRwZW5zLmNvbS9pbWFnZXMvYXNzZXRzL3dhdGVybWFyay5wbmc&markalign64=dG9wLHJpZ2h0&markscale=19&s=938428f6eca690069a86f66d0754444b", "foo":
    "http://assets.sajiansedap.com/media/article_image/cover/large/25505-cara-memilih-nanas-yang-matang.jpg",
     "tux":"https://cdn.shopify.com/s/files/1...;

Answer №4

Let's start by simplifying things before delving into computer vision and related topics:

To establish a connection between two data sets, the key lies in having a relationship. The datasets we are working with consist of:

  1. Text: Descriptive information about the subject.
  2. Link: Reference to an image that represents the subject.

At times, details about the subject (like a green apple) can be inferred from the link itself. However, identifying a pattern in these links or utilizing a dictionary is crucial for effective parsing.

An uncomplicated approach would involve replacing the array of links with an array of objects featuring 2 distinct keys:

  • Text
  • Link

Selecting a random entry from this modified array grants immediate access to both the text and corresponding link. This method is not only streamlined but also allows for seamless addition of more fields as needed.

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

Connecting an HTML button to a Python script

I'm struggling to connect my HTML form with a Python script in order to send an email to the recipient. Despite researching various websites, I can't seem to successfully send the message that I've inputted into the text box. Here's my ...

Whenever I try to relocate my HTML file that references three.js, the three.js library seems to malfunction and stop

Something strange is happening... I recently downloaded three.js into a directory named 'brick': git clone https://github.com/mrdoob/three.js.git which created a subdirectory: brick/three.js/ After navigating to brick/three.js/examples ...

Executing a Jquery AJAX request to generate an authorization code

For my project requirement, I need to generate an authorization code by making a call to the O365 URL using jQuery's AJAX function. The script below is being triggered from the document ready() event. $.ajax({ ...

Utilizing a RESTful approach for ajax requests is effective, but there seems to be a

Trying to make an ajax call and facing some challenges. Used a REST test extension for Chrome called Postman [Link to it]. While the call works fine with the extension, encountering an "error 0" message when trying to send it through jQuery. The request s ...

Display a progress bar in an application to visualize the loading of database records

Within my application, I am accepting a numerical input that is used to generate results on a separate page. The process involves running multiple sequential JDBC queries against Oracle database tables, resulting in a significant delay (1-2 minutes) for th ...

Creating a CSS layout that expands a container to fill the entire height of its grandparent element

Currently, I am developing a web application and facing challenges with the layout. The expected design includes 3 significant components: Article Header Article Content Article Footer Utilizing CSS Flexbox makes it relatively simple to implement this ...

Searching for a file sequence using Regular Expressions in JavaScript

I have a query that needs answering: How can I utilize RegExp in JavaScript to locate strings that adhere to this filter: *[0-9].png for the purpose of filtering out sequences of files. For instance: dog001.png dog002.png dog003.png or xyz_1.png xyz_2 ...

Mapping drop-downs based on the length of a JSON array

Looking to generate dropdowns in a React Native mobile application based on the length of values in an API JSON array. Here's an example of the desired output: eg:- Choice 1 (Label of the Drop Down) -Sub Choice 1 . (Value Data) ...

Enhancing the appearance of a Select element

Alright, let's break it down: I have a custom styled <select> element I want to display an up arrow (possibly a Bootstrap Glyphicon) on the right side of its transparent background The problem at hand: The icon appears correctly (though in ...

What causes the .getJSON function to return a MIME type error when trying to access the API

I've been attempting to make a call to the Forismatic API, but I keep encountering a MIME type error when sending it. JQuery Request: $(document).ready(function() { $("#quote-button").on("click", function(){ $.getJSON("https://api.forism ...

Using onchange within an onchange event will not function as intended

When I am in the process of creating 2 dropdown menus filled from a database, the issue arises when the second dropdown is generated after selecting a value from the first one. Upon choosing an option from the second dropdown, my ajax function is triggered ...

Tips for managing the number of items returned in a dataProvider using AS3

*Hey there! I'm looking to only display 100 items in a list component from a dataProvider, even if it contains more than 500 or even 1000 items. Specifically, I want the first 100 items with cameras on to be included, and then fill the rest to reach a ...

Having trouble with Instafeed JS loading?

I am currently experimenting with instafeed.js, but I am encountering difficulties getting it to load on a basic bootstrap page. While everything else on my page loads successfully, this particular container remains empty without any Instagram code presen ...

Ways to insert text into an SVG file

I am currently using vue-svg-map with a USA map. I am trying to display the state code (path.id) on my svg map. Can anyone provide guidance on how to achieve this? <radio-svg-map v-model="selectedLocation" :map="usa" :location-class="getLocation ...

"Building dynamic web applications using node.js and express.js with routes for

Upon visiting localhost/profil, the CSS styling is working perfectly. However, when I visit localhost/profil/ page, the CSS stops working. app.use(express.static(__dirname+'/public')); app.get('/profil',[checkCo],require('./route ...

The image on my background is getting distorted on Chrome

When using Chrome 27 on a Windows 7 ASUS UX31 laptop (also tested on a MacBook Pro), I encounter an issue on my website, . After scrolling down and back up, I notice that the background image on the carousel is half missing. The problem persists even after ...

The Ajax function effortlessly receives the returned value and smoothly transitions to the error handling stage

When trying to retrieve data from an ajax request, my function needs to receive the returned data as an array of strings. During debugging, I am able to see the response, but at the same time, the error function is triggered. This is how my code looks: ...

How to incorporate Vue3 into Django using CDN without the need for a NodeJs bundler?

When working with Vue2, all I had to do was add the CDN and then Vue would be available in my JavaScript files. However, when trying to use Vue3, my JavaScript files are not detecting Vue. How can I troubleshoot this issue and start using Vue3 successful ...

Encountering connection drops while using AJAX and PHP for Comet implementation on an Apache server

Currently, I am integrating Comet with long-polling AJAX and Apache/PHP. One issue that I have encountered is that if there is a prolonged period of inactivity, meaning no data sent or received, and then an event is triggered after some time, the client- ...

Struggling to manage App navigation using Capacitor event listener (appUrlOpen) in the context of Nuxt, Vue.js, and Vue-Router

I am currently working on a project that involves Nuxt, VueJs, and Capacitor, but I have encountered an issue with routing Firebase dynamic links within the app. Although the iOS App is correctly configured to accept Associated Domains, it runs into diffi ...