Using Javascript to insert an image one by one

keywords = [
    "http://www.website-for-hair.com/", 
    "http://www.website-for-shoes.com/"
]
var keyword = keywords[Math.floor(Math.random()*keywords.length)]

document.write('<a href="'+keyword+'"><img src="http://i.imgur.com/test.jpg" title="Test Title" /></a>');

This code functions as intended when rotating through domains. However, I now need to implement unique images for each website and display the domain along with the corresponding image using +keyword+. Any assistance on how to achieve this would be greatly appreciated.

Answer №1

Here is a method similar to your previous approach:

const pages = [
    { url: "http://page1.com", image: "http://page1.com/logo.png" },
    { url: "http://page2.com", image: "http://page2.com/logo.jpg" }
];

const page = pages[Math.floor(Math.random * pages.length)];

document.write(
    '<a href="' + page.url + '">' +
    '<img src="' + page.image + '" title="foo" />' +
    '</a>'
);

Answer №2

If you're looking to organize your data in a structured manner, consider using a list of lists.

Within this list, each sublist would hold the URL at index 0 (keywords[random_index][0]) and its corresponding image source at index 1 (keywords[random_index][1]).

It's important to save the randomly generated index in a variable so that you can reliably access the same sublist every time.

Here is an example:

keywords = [
    ["http://www.website-for-hair.com/", "imgA"], 
    ["http://www.website-for-shoes.com/", "imgB"]
]

var random_index = Math.floor(Math.random()*keywords.length);
var keyword = keywords[random_index][0];
var image = keywords[random_index][1];

document.write('<a href='+keyword+'><img src='+image+' title="Test Title" /></a>');

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 way to create a fully clickable navbar item for the Bootstrap dropdown feature?

I'm struggling to make a button in a navbar fully clickable for the dropdown to open. Even when I try adding margin instead of padding, it only makes things worse. Can someone help me figure out what mistake I'm making here? Essentially, my goal ...

Does the content only refreshes after the second click, never the first one?

Trying to figure out how to update text in a Bootstrap 3 Popover using JavaScript. I suspect my use of Promises is incorrect because the text only appears in the popover after clicking it twice. The JavaScript code involves calling a local C# Proxy. Here& ...

Should I generate a new object or utilize an already existing one?

When working with JavaScript and needing to replace existing data with new data, what is considered a good or "correct" practice? I currently utilize Dojo's Memory and dGrid to showcase my data. The information is refreshed each time the user clicks ...

Tips for improving the quality of your images

How can I adjust image quality/dpi without changing pixel size? I have an image with a specific pixel size that I need to reduce in quality before saving. If I want to decrease the quality to 87%, how do I achieve this using the following functions? func ...

Issue encountered while configuring 'innerHTML' in xmlHttp.onreadystatechange function

Trying to create a JavaScript function that changes the innerHTML of a paragraph within an xmlHttp.onreadystatechange function, I encountered an error in the Chrome Console: Uncaught TypeError: Cannot set property 'innerHTML' of null at XMLH ...

Which specific transitionend (or animationend) event should I use for this application?

I'm feeling a bit lost when it comes to using transitionend (or if I should be using animationend in this scenario). I'm not sure whether to utilize var, node, or box. Essentially, I am a complete beginner in this case. My goal is to have my div ...

Creating anchor links with #id that function correctly in an Angular project can sometimes be challenging

My backend markdown compiler generates the HTML content, and I need Angular to retrieve data from the server, dynamically render the content, and display it. An example of the mock markdown content is: <h1 id="test1">Test 1<a href="#test1" title ...

Exploring the method of extracting data from PHP arrays through AJAX

Currently, I am using an ajax call to retrieve data from a PHP page. This PHP script is responsible for querying the database between two specified dates. Here is the snippet of PHP code: if(isset($_POST['fromdate'])){ $fromdate = $_P ...

Unable to receive data in an array with Vuejs

Here is the code snippet I am working with: let data = res.data.data; console.log('data: ', data) const list = []; for(let i = 0; i < data.length; i++){ console.log('data i: ', data[i]) //this line is not being printed in the ...

Developing a personalized camera feature using ReactJS

After searching for a suitable npm library to create a custom camera component within my ReactJS project, I came across an article providing detailed information at this link. However, I am facing challenges in converting the existing pure JavaScript code ...

Event triggered when a text input field becomes active (excluding onfocus) in the FireFox browser

I'm currently working on detecting when a text input field is active. Initially, I used the onfocus event, but I encountered an issue where the onblur event would be triggered when the window was no longer in focus, causing unintended consequences in ...

Utilizing JavaScript in Protractor, explore a list to identify the selected checkboxes and those that remain unchecked

Currently, I am working on developing an end-to-end test using Protractor. My main objective is to extract the names from a list and then determine which checkboxes have been selected and which ones haven't. To check the state of the checkbox, I pla ...

Explore the JSON data by iterating through it in NodeJS to identify all potential combinations

Looking for a way to loop through JSON data and identify possible combinations based on input names? Here's the Dimensions array: [ {"value":"zabbixPy-API","name":"ApiName"}, {"value":"qa&quo ...

Getting a JWT token from Express to Angular using ngResource: A step-by-step guide

Currently, I am utilizing a jwt token for user registration validation. A unique URL is generated and sent to the user via email, which leads them to the authentication page. On the server side, the token is decoded and I need to transmit this JSON data to ...

Some parts of the controller exhibit undefined values when accessing the Angular variable, while in other areas, it returns the expected value

I am currently working on a controller where I receive an array of values from a service. Upon receiving the values, I assign the value of a variable as the first element of that array and then perform a console.log to verify the value, which is returned c ...

Trigger $q manually in AngularJS

My understanding of $q in AngularJS is that it runs every time I refresh my page, similar to using a function in ng-init. Here is the code for $q.all that I have: $q.all([$scope.getCart(), $scope.getCategory(), $scope.getMenu(), $scope.getRestaurant()]). ...

What is the best way to attach 'this' to an object using an arrow function?

Consider having an object named profile which consists of properties name and a method called getName (implemented as an arrow function). profile = { name: 'abcd', getName: () => { console.log(this.name); } } I am interes ...

Ways to determine if a web browser is executing javascript code (without altering the javascript on the webpage)

Working on creating a custom PHP client for Selenium, I've encountered an issue with implementing the waitForPageToLoad() function: The problem lies in just checking the document.readyState, as there could be JavaScript scripts running on the page (l ...

Guide to stopping available times from cycling through an array with the help of watch功能?

I am currently developing a booking application within Vue CLI. I have made use of vue-ctk-date-time-picker for selecting the date and time. My goal is to disable certain times based on the chosen date, but I am encountering an issue. The code I have writt ...

I need to update my database by sending requests to my API, as the changes are not being reflected in the current database state. I am eager to see the

Struggling to grasp the concept of making requests to an API that uses express for CRUD operations. In the code snippet below, .get(/bears) displays a form and in app.post('/bears'), I'm using the 'request' module to send a request ...