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

Managing AJAX Errors in PHPAJAX error handling tips for developers

My current code is only set up to display a general error message when an error occurs during execution. I want to improve it by returning specific error messages for different scenarios. However, I have not been able to find satisfactory solutions in my s ...

What are the steps to testing an endpoint with Jasmine/Karma?

Within one of my components, there is a method that makes a call to an endpoint in the following manner... private async getRolesAsync(): Promise<void> { const roles = await this.http.get<any>('https://sample-endpoint.com').toProm ...

Tips on restricting users to choose dates that are later than the current date

Currently, I am working with Vue3 using the options API. After reviewing this StackBlitz, my question is regarding how to correctly set the :max value for a date-picker. Even though I have assigned :max as new Date(), I am still able to select dates that ...

Exploring Node.js and Express routing: Strategies for managing client-side promises

I've been working on a routing issue with MongoDB where I'm having trouble retrieving data on the client side from the promise received via $resource. There's a button on the HTML page that triggers the following function on ng-click: $scop ...

How to unselect a radio button in Vue using a button, similar to using vanilla JavaScript

Looking to translate this vanilla JavaScript code into Vue, here's the original: const radio = document.querySelector('#radio'); const boton = document.querySelector('#boton'); boton.addEventListener('click', () => { ...

Passing data between parent and child components within an Angular application using mat tab navigation

I am currently working on a project, which can be found at this link. Current Progress: I have implemented a mat tab group with tabs inside the app-component. When a tab is clicked, a specific component is loaded. Initially, most of the data is loaded in ...

Sequence of HTML elements arranged in a stack

Recently, I came across a useful jQuery tutorial called "jQuery for Absolute Beginners: Day 8". In this tutorial, there is an interesting code snippet that caught my attention: $(function() { $('.wrap').hover(function() { $(this).childre ...

Leveraging the power of React's callback ref in conjunction with a

I'm currently working on updating our Checkbox react component to support the indeterminate state while also making sure it properly forwards refs. The existing checkbox component already uses a callback ref internally to handle the indeterminate prop ...

graphic map and paintbrush

I've implemented an image map using shape circles, but now I'm looking for a way to draw visible circles or icons on the map. Is there a solution for this issue? Currently, I have used a canvas overlay on the image to draw on it This method wo ...

Keep track of the current state as the page changes with React Router

I am experiencing an issue with my React component. const Page = React.createClass({ getInitialState() { return { page: {} }; }, componentDidMount() { const pageId = this.props.params.pageId; socket.emit('get page', pageId, (pa ...

Guide on saving the highest score in a game using JavaScript with an if statement

I am currently working on a practice game that involves counting the number of taps made within 3 seconds. I've completed everything except for implementing the functionality to save the high score and display the previous best score if there isn&apos ...

The parameter 'data' is assumed to have an 'any' type in React hooks, according to ts(7006)

It's perplexing to me how the 7006 error underlines "data," while in the test environment on the main page of React Hooks (https://react-hook-form.com/get-started#Quickstart), everything works perfectly. I'm wondering if I need to include anothe ...

Looking to include a data-* attribute within a div element for the utilization of a third-party JavaScript library like React or Next.js?

let speed = '{ "speed": 0.2 }'; <div className="section jarallax h-100vh" data-jarallax={speed} style={{backgroundImage: "url('/images/header-bg.jpg')"}} id="home"> </div> <Script src="./js/parallax.js" strate ...

Prevent user input in calendar view using HTML classes

Need help adding a date picker to my code. Below is the snippet of code: The issue I am facing is that I want to prevent users from manually typing in dates. <div class="form-group clearfix"> <label class="col-lg-4 control-label">Date Sold ...

Initiating a Page with Dynamic Modal Window according to Backend Exigencies

Dear experts, can you help me with a problem? I want to implement a modal window on an vb.aspx page if a specific condition from the codebehind query is true. How can I achieve this? Thank you! ...

In Angular, when a promise returns an "undefined" value, how does this interact with .NET

When I execute this code snippet, I am encountering an issue where the response returned is "undefined" instead of the expected value. Here is the code in question: $scope.SameNameFunction = function() { var payload = { itemname: $scope.EventD ...

Creating dynamic cubes in Magento with interact.js within a .phtml template

I utilized the interact.js library to create this code snippet, which functions perfectly on Chrome, Firefox, and w3schools "Try it Yourself" platform (unfortunately not compatible with Edge and IE for unknown reasons). However, when I include this code wi ...

What is the process for advancing to the next or previous step using Angular.js?

I am currently utilizing ui-route for routing purposes, specifically for navigating through a series of sequential forms. After submitting one form, I would like to automatically move on to the next step without hard coding the step name in the $state.go( ...

Show a modal component from another component in Angular 2

As a newcomer to Angular, I'm working on a modal component that changes from hiding to showing when a button with (click) is clicked. The goal is to integrate this modal into my main component, allowing me to display the modal on top of the main conte ...

Is there a way to dynamically adjust the form action based on whether or not JavaScript is enabled?

Is there a way to make a form default to calling a JavaScript ajax function for output, but switch to a PHP page if the user doesn't have JavaScript enabled? <form class="form-inline" role="form" action="javascript:search();"> <div class=" ...