Is there a way to open various href links with distinct images using window.open?

I am facing some limitations with the program, therefore it would be preferable if

the solution does not require JQuery, as mentioned earlier. There are certain

restrictions that need to be taken into consideration.

My objective is to:

  1. Dynamically change an image using JavaScript. (Completed)

  2. Ensure that each image redirects to a different link when clicked by the user. (Need assistance!)

Below is the code I am currently working with:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

var image1=new Image()
image1.src="image_1.jpg" 

var image2=new Image()
image2.src="image_2.jpg"

var image3=new Image()
image3.src="image_3.jpg"

var step = 1 

function slideit(){

document.images.slide.src=eval("image"+step+".src")

if(step<3) step++

else step=1

setTimeout("slideit()",2500)

}

slideit()

function inputhref() {

var href = 'https://www.google.ca/';

window.open(href)

}
</script>
</head>
<body>
<img src="image_1.jpg" name="slide" width="400" height="400" 
 onclick="inputhref()">

Answer №1

I encountered a few issues, but through troubleshooting and perseverance, I managed to fix them successfully!

  1. To open a URL in the same window, I utilized window.location.href.

  2. For selecting element(s), I employed document.querySelector().

  3. When utilizing the setTimeout() function, I made sure to call it with the function name without using ''.

<!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <img src="image_1.jpg" id="slide" width="100" height="100" 
     onclick="inputhref()">
     
     
    <script type="text/javascript">

    var image1=new Image()
    image1.src="https://image_1.jpg" 

    var image2=new Image()
    image2.src="https://image_2.jpg"

    var image3=new Image()
    image3.src="https://image_3.jpg"
    
    var step = 1 
    var slide = document.querySelector('#slide');
    var timer

function slideit(){

slide.src="https://image_"+step+".jpg"

if(step<3) step++

else step=1
  console.log('Image changed to ' + slide.src);
timer = setTimeout(slideit,2500)

}

slideit();

    function inputhref() {

window.location.href = slide.src;
  clearInterval(timer);

}
    </script>
</body>
</html>

Answer №2

To streamline your process, consider creating an object that can store both the image source and its corresponding link. If you are only using the Image() classes for setting and retrieving URLs, you could simplify by storing them as strings within the object. It's also beneficial to include the step as a property and organize all images in an array for easy access.

Here's a suggested format:

var images = [
    {
        step: 1,
        src: "image_1.jpg",
        link: "http://example.com/image1-link",
    },
    {
        step: 2,
        src: "image_2.jpg",
        link: "http://example.com/image2-link",
    },
    // Add more as needed
]

Adjust your functions accordingly:

function slideit() {
    var currentImage = images.find(image => image.step == step);
    document.images.slide.src = currentImage.src;
    // Keep other functionality the same
}

function inputhref(step) {
    var currentImage = images.find(image => image.step == step);
    window.open(currentImage.link);
}

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

Guide to generating interactive material-ui components within a react application?

I am facing a challenge in creating a dynamic mui grid element triggered by a button click in a React component. When attempting to create let newGrid = document.createElement('Grid'), it does not behave the same way as a regular div creation. D ...

What is the rationale behind Typescript permitting the assignment of an "any" object type to a class object?

Within my codebase, there is a class object that I have initialized: groupNameData: GroupNameData = new GroupNameData(); In addition, I also have an any object called groupNameDatas. groupNameDatas: any; Experiment 1 (class = any) To experiment with ...

Adding a PDF generated from an HTML div to an email using Java

I am looking for a solution to convert the contents of an HTML div tag into a PDF file while preserving its associated CSS. This is essential as I will be using Java on the back-end to send emails, and I need to attach the PDF with the CSS intact when send ...

Incorporate the Google Maps API into a React application

I've recently started learning react and I'm currently trying to integrate the Google Maps API into my React application. Within my app, I have a search input field and a designated area for the map located at http://localhost:8080/. My main qu ...

Search through the JSON data, identify similar values, and save them in a collection

Struggling to find a way to limit the output of my comparison between attribute values in an object, I am only looking for one output per ID. Any suggestions? //example JSON var obj1 = { "Summary" : [ { "ID" : "1234", "Name" : "Joh ...

Issue: Trouble with Rotating Tooltips in Javascript

I am facing a challenge with the tooltips on my website. I want to ensure that all tooltips have a consistent look and transition effects, but I am struggling to achieve this. The rotation and other effects applied using javascript are not functioning prop ...

A new sub-schema has been created in the JSON schema specifically tailored to a certain property

I needed to create a JSON schema with 3 fields: num, key1, and key2. The fields num and key1 are required, while the field key2 is only mandatory if key1 has a value of 'abc'. Below is the schema structure I came up with: schema = { type: &ap ...

Unable to store the hashed password using bcrypt

I've been working on persisting hashed passwords using sequelize, bcrypt, and express. While the hash is being generated, it seems like the database entry occurs before the hash value is ready. My understanding of NodeJS is still in its early stages. ...

What is the best way to convert the <br /> tag name into a white space in sanitize-html JavaScript?

I have some HTML code that looks like this: "<p>Hello world!<br/>I am here</p>" I need to replace the code with the following output: "<p>Hello world! I am here</p>" Is there a way to achieve this using t ...

Guide on establishing a connection to a server from a local database

Attempting to access an external database locally through my server, I ran the following code on the server side: console.log('MONGODB_URI_LOCAL::', config.MONGODB_URI_LOCAL) const mongooseLocal = require('mongoose'); const connectionO ...

Determining the minimum and maximum values of a grid using props in a React component

I have created a code for a customizable grid screen that is functioning perfectly. However, I am facing an issue where I want the minimum and maximum size of the grid to be 16 x 100. Currently, when a button is clicked, a prompt window appears asking for ...

Utilize npm module by directly installing from GitHub repository

After finding that an npm package I wanted to use in my Meteor app was missing some features, I decided to take matters into my own hands. I forked the repo and applied the patch myself. To install the updated package, I used the following command: meteor ...

Tips for preventing users from entering special characters into input fields

How can I prevent users from entering the # character into an HTML input field? I attempted to use the pattern attribute, but it does not seem to be effective. I included this pattern in my input element: pattern="[^-#]+" I expected that this would disa ...

Bindings with Angular.js

I have developed an application similar to Pastebin. My goal is to allow users to paste code snippets and display them with syntax highlighting and other visual enhancements, regardless of the programming language used. To achieve this, I utilize Google&ap ...

Converting a JSON list into a JavaScript object for the purpose of creating a dynamic

Understanding how JSON's lists work when parsed as JavaScript objects is challenging for me. I am not very familiar with JavaScript, so there may be mistakes in my question and the proposed solution. Currently, I have a JSON file that needs to be conv ...

Having an issue with displaying the country name and country code in a table using the Angular7 custom pipe

country code: "ab", "aa", "fr", ... I need to create a custom pipe that will convert a countryCode into a countryName, such as: "ab" → "Abkhazian", "ch" → "Chinese", "fr" ...

Cocos2D-JS is unable to import a json file that has been exported from CocosStudio

Trying to import a json file that was exported from cocosstudio v2.3.2 var myScene = ccs.sceneReader.createNodeWithSceneFile('res/Scene.json'); Found this code in the sample-cocos2d-js-scene-gui-master repository. Encountering an error: Can& ...

Generating directives on the fly

I am relatively new to AngularJS and have a good understanding of the basics. My goal is to create a desktop interface where items are loaded dynamically from a database using $http. I have already developed a directive that displays a title and an icon fo ...

Navigation menu featuring unique links for varying pages

This application is built on Ruby on Rails, using Ruby version 2.1.4 and Rails version 4.1.14. I have a Javascript dropdown menu in the header bar that displays a list of items. However, I'm struggling to figure out how to dynamically change the menu ...

Working with JavaScript's push() method for JSON data manipulation

How can I populate a JSON variable with data in the following format? [ "name":"sample name" ,"first_name":"sample first" ,"last_name":"sample last" ,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6c5d7dbc6dad398f6d ...