Change the behavior of JavaScript so that it executes when clicked, not when the

This script is currently set to run when the page loads:

<script language="JavaScript"> 
     j=parseInt(Math.random()*ranobjList.length);
     j=(isNaN(j))?0:j;
     document.write(unescape(ranobjList[j]));
</script>

Is there a way I can make it execute only when a button is clicked, instead of automatically loading?

Answer №1

Encapsulate it within a function and trigger it when an element is clicked

function generateRandomContent() {
    let index = parseInt(Math.random() * contentList.length);
    index = (isNaN(index)) ? 0 : index;
    document.write(unescape(contentList[index]));
}

Then in your HTML file

<input type='button' value='Generate Content' onclick='generateRandomContent();' />

Answer №2

The snippet provided is not executed on page load but rather when it's parsed by the DOM.

However, here's a solution to address your query.

Make sure that the HTML button precedes the script tag. You can achieve this with code similar to the following:

<input type="button" value="Click me for action" id="actionButton" />

<script type="text/javascript">
    document.getElementById("actionButton").addEventListener("click", function() {
        j=parseInt(Math.random()*ranobjList.length);
        j=(isNaN(j))?0:j;
        document.write(unescape(ranobjList[j]));
    }, false);
</script>

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

Transmit messages from server (via Expressjs routing) to the client

I am looking for guidance on how to effectively send messages from the server to the client and incorporate this functionality into routes/index.js within my mean stack project. Can anyone provide insights on using socket.io in this context?: router.post( ...

Display a JSON object on a web browser

I am trying to display a JSON object on a web browser using HTML. The object is already in a text file and has been properly formatted for readability. My goal is to maintain the same formatting when displaying it on the browser. ...

The type 'number[]' is lacking the properties 0, 1, 2, and 3 found in the type '[number, number, number, number]'

type spacing = [number, number, number, number] interface ISpacingProps { defaultValue?: spacing className?: string disabled?: boolean min?: number max?: number onChange?: (value: number | string) => void } interface IFieldState { value: ...

Elegant transition effects for revealing and hiding content on hover

While customizing my WordPress theme, I discovered a unique feature on Mashable's website where the social buttons hide and show upon mouse hover. I'd love to implement this on my own site - any tips on how to achieve this effect? If you have ex ...

How to retrieve the value from an editable td within a table using Jquery

I am working with a dynamic table that looks like this: <table> <tbody> <tr> <td>1</td> <td contenteditable='true'>Value1</td> </tr> <tr> ...

Using Selenium WebDriver to handle Angular requests in Java

I am currently developing tests for an angular-based application and I find myself in need of assistance. The specific task at hand involves creating a mechanism that will wait until all pending requests within the application have been processed before pr ...

Cease animation if the page has already reached its destination

In my current setup, I am using a JavaScript code snippet to navigate users to the specific location of the information they click on in a side navigation menu. However, one issue that arises is if they first click on one item and then another quickly, t ...

prompting the JavaScript hangman game to identify the letters in the "selected word"

Currently, I am on a mission to teach myself Javascript and have taken on the challenge of creating a simple hangman game. This type of project is commonly used in interviews or tests, so it seemed like a great opportunity for practice. My approach involve ...

Pause and wait for the completion of the Ajax call within the function before assigning the object to an external variable

In my quest to leverage JavaScript asynchronously to its full potential, I am looking for a way to efficiently handle received data from API calls. My goal is to dynamically assign the data to multiple variables such as DataModel01, DataModel02, DataModel0 ...

Is innerHTML incapable of executing JavaScript code?

Experimenting with a new technique where I divide my code into separate files to create multiple HTML pages instead of one large one. Using ajax to load them and then setting the content as innerHTML to a parent div results in clean code that works well in ...

Why are my API routes being triggered during the build process of my NextJS project?

My project includes an API route that fetches data from my DataBase. This particular API route is triggered by a CRON job set up in Vercel. After each build of the project, new data gets added to the database. I suspect this might be due to NextJS pre-exe ...

Sending Data from jQueryUI Dialog to PHP using AJAX

I am struggling to retrieve the user inputs from text fields within a dialog window in order to utilize them for a SQL query. The issue I am encountering is that I am unable to effectively use the array in PHP. Despite no error messages being displayed, I ...

Challenges in creating an alternative path in ExpressJS

I am currently working on a website for my studies. I decided to use nodejs/Express, as the technology is free. The first route /home was successful, but I am having trouble creating more routes. Although I thought I had a good understanding of the system ...

Updating of an Angular Directive within a nested Directive ceases once the inner Directive has been modified

Encountered a challenge with directives nested within each other in AngularJS. The issue is that both directives share the same property through a service and have an input to modify this property. The outer directive uses "transclude" to include the inner ...

When employing UI-Router, custom directives may not function properly within nested views

I was developing an angular application using phonegap, ionic, and angular. I had created a custom directive that registered an event listener for the element to activate iScroll upon loading. Initially, the directive worked perfectly when all the views we ...

JavaScript - convert the values of an array within a JSON object into separate strings

I am receiving a JSON object from an API, and my next step involves some string analysis of each key value. This process works perfectly for 90% of the objects I receive because the key values are strings. { ID: '0012784', utm_source: 'webs ...

Encountering a 'TypeError: app.address is not a function' error while conducting Mocha API Testing

Facing an Issue After creating a basic CRUD API, I delved into writing tests using chai and chai-http. However, while running the tests using $ mocha, I encountered a problem. Upon executing the tests, I received the following error in the terminal: Ty ...

What is the best way to apply the TableRow style in material-ui / mui to make it similar to TableHead?

Trying to implement TableHead styling on TableRow but encountering a warning: validateDOMNesting(...) cannot be a child of. How can this be fixed without triggering a warning message? CollapisbleTableRow.js import React, { Fragment, useCallback } from &ap ...

How can I customize the <span> element created by material-ui?

Is there a way I can customize the appearance of the <span> tag that is produced when using the Checkbox component from the material-ui library? Essentially, I am seeking a method to alter: <span class="MuiButtonBase-root-29 MuiIconButton-root-2 ...

Modify the hover color of <TextField /> within the createMuiTheme() function

Is there a way to change the borderColor on hover for the outlined <TextField /> Component within the createMuiTheme()? I have managed to do it easily for the underlined <Input /> export default createMuiTheme({ MuiInput: { &apo ...