create hyperlinks based on div clicks in HTML using JavaScript

Hey there! I'm working on a cool animation for my page that involves a star fade effect. After the animation, I want to open a link to another page on my site.

Imagine I have 3 cards on my page, and when I click on any of them, I want the same animation to play, followed by a 1500ms delay, and then the new page opens in the same tab.

I'm thinking of setting the link information in the HTML using either the a href tag or window.location, and then using a JavaScript query to retrieve that information.

I apologize if my explanation is a bit unclear, I'm still very new to JavaScript and learning as I go!

HTML

<div class="link1" window.location="index1.html"></div>           
<div class="link2" window.location="index2.html"></div>
<div class="link3" window.location="index3.html"></div>

Javascript

open() {

this.isOpened = true;

this.elm.classList.add('is-opened');

this.timeStart = Date.now();

this.renderLoop();

setTimeout(function() { window.location = document.getElementsByName('window.location')}, 1500);

  }

Answer №1

Here is a method to assign URLs to the attribute data-link. For example:

const hyperlinks = document.querySelectorAll('.hyperlink');
for(var hyperlink of hyperlinks) {
  hyperlink.addEventListener('click', function(event) {  
    setTimeout(function() {
      window.open(event.target.getAttribute('data-link'), '_blank');
    }, 1500)
  })
}
<div class="hyperlink" data-link="page1.html">Page 1</div>
<div class="hyperlink" data-link="page2.html">Page 2</div>
<div class="hyperlink" data-link="page3.html">Page 3</div>

If you prefer to open the links in new tabs, make sure that 'allow-popups' permission is granted in most browsers. Otherwise, simply replace

window.open(event.target.getAttribute('data-link'), '_blank');

with

window.location = event.target.getAttribute('data-link');

Answer №2

  1. When defining an attribute, ensure you reference it correctly as name - using "window.location" and document.getElementsByName. Remember that document.getElementsByName returns an array, so you must access it as document.getElementsByName[0]. Additionally, avoid naming conflicts by using a different name instead of the predefined method "open", and call it upon a click event on the divs.

  2. To achieve your desired outcome, consider the following implementation:

function openLink(element) {
  // Implement other necessary animation tasks
setTimeout(function() { 
  window.location = element.getAttribute("data-location");}, 1500); // element refers to the div element, retrieving the data-location attribute containing the URL to open
  }
<div class="link1" data-location="index1.html" onclick="openLink(this)">asdas</div>           
<div class="link2" data-location="index2.html" onclick="openLink(this)"></div>
<div class="link3" data-location="index3.html" onclick="openLink(this)"></div>

Visit the provided fiddle link for a demonstration: https://codepen.io/ajanth2012/pen/MXaPpp

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

How can an array of file paths be transformed into a tree structure?

I am looking to transform a list of file and folder paths into a tree object structure (an array of objects where the children points to the array itself): type TreeItem<T> = { title: T key: T type: 'tree' | 'blob' childr ...

Issues with z-index in a multi-column menu using React-Router are causing unexpected behavior

I am currently working on a multi-tier, multi-column menu created using the https://github.com/kontentino/react-multilevel-dropdown library. However, I am facing an issue where the submenu items are appearing under the main items despite several attempts t ...

Is it necessary for NPM to execute scripts labeled as dependencies during the npm i command execution?

When npm i is run, should it execute the scripts named dependencies? I've observed this behavior in the latest version of Node (v19.8.1) and I'm curious if it's a bug. To replicate this, follow these steps: mkdir test cd test npm init -y T ...

Verifying the user's email and password for authentication

Is there a way to verify the authenticity of the email and password entered in the form, so that I can redirect to a new page? Unfortunately, upon reloading the page, the validation process seems to fail in checking whether the user email and password are ...

Mootools tweening color transition denied for child elements when color is explicitly defined in CSS

Check out this link for testing: http://jsfiddle.net/EnJSM/ You might observe that by removing "color: #6CB5FF;", the transition behaves differently - it only works for the second part of the line. I'm interested to see what solution you come up wit ...

Checking the status of a Cisco Jabber user using JavaScript

How can I verify on my webpage if a user is available on the Cisco Jabber Client? I have both their number and username. I can currently send chat messages and start voice conversations, but I would like to display a cool icon or indicator if the user is o ...

Angular allows for dynamic sourcing of iframes

I have encountered an issue while trying to integrate a payment system with Angular. The payment gateway API I am using provides the 3D Secure Page as html within a JSON response. My approach is to display this html content within an iframe, however, the h ...

Looking for assistance in streamlining the code

On my Drupal page, I have multiple divs and a JavaScript function that checks for content inside each one: if ($('.accred').length) { $('#accred').show(); } else{ $('#accred').hide(); } // More code follows... T ...

Submitting forms using Ajax within a modal pop-up box

Here's an interesting issue that I'm facing: On a test page, when the user clicks to view results, a modal box opens with 3 select boxes. Select Box 1 populates Select Box 2, which then populates Select Box 3 The Problem: After clicking submi ...

Having issues transferring values from one page to another. Any suggestions to make it work correctly?

I currently have two pages within my website, one is called details.page and the other is maps.page. In the details page, I have set up a search input as shown below : <form method="get" id="form-search" data-ajax="true" action="maps.page"> ...

Whenever I use NextJS's <Link> component, I always end up getting redirected to a

After searching online, I came across this question and tried to implement the suggested solution, but it's still not working for me. Apologies for any duplication. I have a simple link tag that is resulting in a 404 error: <Link className={classe ...

spring fails to run javascript

In my project, I am utilizing Spring MVC 3 framework. Below is the snippet of my AddressController: @Controller public class AddressController { private static Logger logger = Logger.getLogger(AddressController.class); @RequestMapping(value="/ad ...

Utilizing an AngularJS factory to retrieve JSON data from the server

I have a large JSON object in my controller that I want to move to a separate file. Currently, this is how I'm approaching it: myApp.controller('smController', ['$scope', function($scope) { ... var stadtmobilRates = { cla ...

Issue with highlighting when one string overlaps with another

I am facing a challenge with handling a string that contains Lorem Ipsum text. I have JSON data that specifies the start and end offsets of certain sections within the text that I need to highlight. The approach I am currently using involves sorting the JS ...

Wait for a for loop to finish before triggering a function in Node.js

Hey there! I'm a newbie when it comes to node.js and I feel like I'm stuck in callback hell at the moment. I've gone through various similar questions but still struggling to make my code work properly. Basically, what I'm trying to do ...

What steps can a web developer take to view user console errors?

Is there an effective method for a web developer to receive notifications of console errors logged by other authorized users? I am currently working with Express, Passport, and MongoDB. These errors may occur on either the client or server side. One approa ...

Is there a way to eliminate spaces from a string using react-native?

As a user of react-native, I've encountered an issue with inconsistent line breaks when inputting long strings on the screen. For example: https://i.sstatic.net/32RwW.jpg I aim to achieve consistent string wrapping as shown in the image below: htt ...

AngularJS: The dynamic setting for the stylesheet link tag initiates the request prematurely

I'm encountering a problem that is somewhat similar (although not exactly the same, so please be patient) to the one discussed in Conditionally-rendering css in html head I am dynamically loading a stylesheet using a scope variable defined at the sta ...

Can an AJAX request continue running even after the user has moved to a different page within the website?

Currently on my website, users are able to submit a form using ajax. The response, indicating whether the form was successfully submitted or if there was an issue, is displayed in an alert message. However, due to the asynchronous nature of this process, i ...

Add a hovering effect to images by applying the absolute positioning property

On my React website, I am utilizing Tailwind CSS and I am attempting to showcase an image that has interactive elements. I want certain parts of the image to increase in size slightly when hovered over. My approach to achieving this was to save each part o ...