Using Javascript to generate a button that randomly chooses links within the webpage

Looking for help with JavaScript to select a link when a button is clicked on the page? Check out my code and let me know what I'm doing wrong.

For the full code, visit: here

HTML

<!doctype html>
<html lang="it" xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<!--Code truncated due to character limit-->

Javascript

//Variable declaration

let button = document.getElementById("random-select");
let tab1 = document.getElementById("pastichair");
let tab2 = document.getElementById("bella-e-brava");
let tab3 = document.getElementById("personal-space");

//Array and function to generate random number between 0 and 2
let array = ["headerA", "headerB", "headerC"];

button.addEventListener("click", tabRandom())

function tabRandom () {
    let randomNumber = Math.floor(Math.random() * array.length);

    //If statement to select a random tab
    if (randomNumber === 0) {
        tab1.addEventListener("click", function (){
            document.getElementById("pastichair").click();
        });
    }
    if (randomNumber === 1) {
        tab2.addEventListener("click", function (){
            document.getElementById("bella-e-brava").click();
        });
    }
    if (randomNumber === 2) {
        tab3.addEventListener("click", function (){
            document.getElementById("personal-space").click();
        });
    }
}

Answer â„–1

If you want to ensure it functions properly, there are a couple of adjustments you can make.

Firstly, modify the callback parameter like so:

// The following is incorrect as it executes a function and passes its value as a callback
button.addEventListener("click", tabRandom());

// To correctly pass a function as a callback
button.addEventListener("click", tabRandom);

Next, within the tabRandom() function, you need to eliminate the addEventListener in order for the trigger to work:

// This will not work as it assigns an event
tab1.addEventListener("click", function (){
   document.getElementById("pastichair").click();
});

// Triggering a click event instead
document.getElementById("pastichair").click();

For further reference, check out this CodePen 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

Implementing form validation for dropdown lists with Material-UI React: A comprehensive guide

I'm still learning React and I've been using material-ui for form validation. Everything was going smoothly until I encountered an issue with validating a dropdown list. Whenever I try to validate it, an error occurs: "Cannot read property ' ...

Angular: Preserve the URL even when encountering a 404 page

Creating a custom 404 page in Angular 4 is something I have recently done, and I am looking for a way to preserve the incorrect URL that was input by the user. To see an example of this behavior, you can visit sites like GitHub. They show a 404 page when a ...

Javascript error specific to Internet Explorer. Can't retrieve the value of the property 'childNodes'

After removing the header information from the XML file, the issue was resolved. Internet Explorer did not handle it well but Firefox and Chrome worked fine. An error occurred when trying to sort nodes in IE: SCRIPT5007: Unable to get value of the proper ...

JavaScript: A guide on sending an uploaded email to a web service in byte array format

Scenario: My website is built using EXTJS6. I have a web service that requires the uploaded email to be sent in byte array format. Inquiry: What is the process for converting a .msg file to a byte array using JS (or EXTJS)? Can we treat it as a simple bin ...

The Angular Material date picker unpredictably updates when a date is manually changed and the tab key is pressed

My component involves the use of the Angular material date picker. However, I have encountered a strange issue with it. When I select a date using the calendar control, everything works fine. But if I manually change the date and then press the tab button, ...

Adjust the size of the input form

Trying to create this design: But currently stuck with this layout: I'm puzzled on how to resize the input field with an icon on the right while using col-md-12... Check out my code below: .form { margin-top: 8px; margin-left: 13px; displ ...

The console correctly detects the value, but is unable to set the innerHTML property of null

I am currently working on a webpage that allows users to sign in and create an account. The issue I'm facing is that when I try to display the user's information, I encounter the error 'Cannot set property 'innerHTML' of null.&apos ...

Asynchronous update of array elements - lack of firing watch events

I have recently developed a component that showcases previews of blog articles. This particular component includes pagination functionality, where selecting a new page triggers the refreshment of the article previews array. The list of articles is obtained ...

Displaying numerous Google maps on a single webpage featuring distinct collections of location markers

Currently, I am utilizing the Google Maps API to showcase two distinct Google maps on a single page. Each map comes with its own set of unique markers that are dynamically generated via Wordpress from various custom post types. While one map is successful ...

After refreshing, the base href in the environment is characterized as undefined

Within my angularjs application, I have configured the env.js file as shown below: (function (window) { window.__env = window.__env || {}; // API url window.__env.apiUrl = 'http://aaaaaaa.com/'; // Base url window.__env.baseUrl = '/angula ...

unable to see the new component in the display

Within my app component class, I am attempting to integrate a new component. I have added the selector of this new component to the main class template. `import {CountryCapitalComponent} from "./app.country"; @Component({ selector: 'app-roo ...

React - Obtain User Login Details and Verify

I am working on a React project that includes a Login Form. The code has been organized into small components for reusability, but I am unsure of how to retrieve and validate user credentials (username and password). Is there a method available to validate ...

Modifying the color of drawings on a Javascript canvas

I am currently working on developing a drawing board using HTML and JavaScript (Node.js on the server side). One challenge I'm facing is implementing a color picker that allows users to change the paint color dynamically. While I could hard code the c ...

How to extract information from a shared notebook on Evernote using Python

Trying to retrieve data from a shared Evernote notebook, such as this one: Initially attempted using Beautiful Soup: url = 'https://www.evernote.com/pub/missrspink/evernoteexamples#st=p&n=56b67555-158e-4d10-96e2-3b2c57ee372c' r = requests.g ...

What is causing the issue with Vue.js :class not functioning properly when it relies on a property of a list

Here is a snippet of my HTML code: <tr v-for="product in products" :class="{'bg-red': product.toWrite }" :key="product.name"> <td @click="setObjectToWrite(product.name)" class="show-hover&qu ...

Learning how to interpret data within configuration files (.properties) using JavaScript

I'm trying to retrieve data from a configuration file (.properties) in my code. The structure of my configuration file is as follows: maxTime = 60 upVotePostMaxTime=60 However, I am unsure of how to read this configuration file using JavaScript. Is ...

What is the method for retrieving a value from my Node.js module once it has been modified by an asynchronous function?

Apologies, but as a beginner developer, I'm struggling to see how this relates directly to the questions already mentioned. I have no understanding of ajax and I'm unsure how to adapt the solutions provided to my own situation. Currently, I&apos ...

Configuring cloud code on Back4App to automatically trigger a POST API request to update the ESP

I am a beginner when it comes to developing APIs and cloud code, and I need help figuring out how to create an API that can add or update users in my back4app database table to my sendinblue (ESP) contact list. Could someone provide guidance on what shoul ...

Filtering an array within an array based on user input

I am currently facing a challenge in filtering the child elements of an array. I am puzzled on how to specifically target children elements. So far, my filter is only functioning at the top level. Array: options: [ {name: 'Ð’Ñ‹Ñ…Ð ...

In order to add value, it is necessary to insert it into the text box in HTML without using the "on

example <input type="text" id="txt1" onChange="calculateTotal();" /> <input type="text" id="txt2" onChange="calculateTotal();" /> <input type="text" id="txt3" onChange="updateValue();" readonly/> <input type="text" id="txt4" onChange= ...