Change the colors and messages shown when the button is clicked or hovered over

I'm seeking assistance in getting this code to function properly, specifically to display different colors and messages when specific buttons are clicked or hovered over.

My goals are:

  1. To change the background color of the page when the button 'colors' is hovered over
  2. To show a message when the button 'msg' is clicked

As a beginner, I'm not sure what's wrong with the code, but I do know that the functions aren't triggering automatically.

<!DOCTYPE html>
<html>

<head>
  <title></title>
</head>
<script language="javascript">
  function f1() {
    document.bgcolor = "blue";
    window.setTimeout("f2", 1200);
  }

  function f2() {
    document.bgcolor = "indigo";
    window.setTimeout("f3", 1200);
  }

  function f3() {
    document.bgcolor = "violet";
    window.setTimeout("f4", 1200);
  }

  function f4() {
    document.bgcolor = "green";
    window.setTimeout("f5", 1200);
  }

  function f5() {
    document.bgcolor = "purple";
    window.setTimeout("f6", 1200);
  }

  function f6() {
    document.bgcolor = "yellow";
    window.setTimeout("f7", 1200);
  }

  function f7() {
    document.bgcolor = "orange";
    window.setTimeout("f8", 1200);
  }

  function f8() {
    document.bgcolor = "red";
    window.setTimeout("f1", 1200);
    f1();
  }

  function msg() {
    window.status = "displaying 7 distinct colors"
  }
</script>

<body>
  <center>
    <input type="button" name="b1" value="colors" onMouseOver="f1()">
    <input type="button" name="b2" value="msg" onClick="msg()">
  </center>
</body>

</html>

Answer №1

It seems like this solution might be what you're seeking. Instead of using JS, which can lead to a "Maximum Call Stack Trace Exceeded" error that is unmanageable, I found a workaround by incorporating CSS animations in an inline stylesheet. The colors change every 1200ms, triggered by the button enabling the stylesheet instead of directly setting the color. This approach ensures smooth color transitions without encountering any stack trace issues.

In addition, to address browser compatibility concerns related to window.status, I switched to window.alert as a supported alternative.

  <!DOCTYPE html>
  <html>
  <head>
      <title>Colors</title>
  </head>
  <script language="javascript">
  window.onload = function() {
      document.getElementById("style").disabled=true;
  }
  function colors()
  {
      document.getElementById("style").disabled=false;
  }
  function msg()
  {
      window.alert("display 7 distinct colours");
  }
  </script>
  <body>
  <style id="style">
      body {
          animation-duration: 8400ms;
          animation-name: bgcolorchange;
          animation-iteration-count: infinite;
          animation-timing-function:steps(1, end);
      }
      @keyframes bgcolorchange {
          0% {
              background-color: blue;
          }
          12.5% {
              background-color: indigo;
          }
          25% {
              background-color: violet;
          }
          37.5% {
              background-color: green;
          }
          50% {
              background-color: purple;
          }
          62.5% {
              background-color: yellow;
          }
          75% {
              background-color: orange;
          }
          87.5% {
              background-color: red;
          }
          100% {
              background-color: blue;
          }
    }
    </style>
    <center>
        <input type="button" name="b1" value="colors" onMouseOver="colors()">
        <input type="button" name="b2" value="msg" onClick="msg()">
    </center>
</body>

</html>

Answer №2

Are you in search of something specific?

Here is a straightforward Javascript solution:

  var bx = document.body;
  var colorArr = ["blue", "indigo", "voilet", "green", "purple", "yellow", "orange", "red"];
  var counter = 0;
  var ifHover = false;
  var interval;

function changeClr() {
  if(ifHover != true) return;
  bx.style.background = colorArr[counter];
  counter++;
  if(counter==colorArr.length) counter=0;
  interval = setTimeout(changeClr, 1200);
}

function startClr(){ ifHover = true; clearInterval(interval); changeClr(); }

function stopClr(){ ifHover = false; }

function msg() {
  alert("display 7 distinct colours");
}
<center>
  <input type="button" onmouseover="startClr()" onmouseout="stopClr()" value="color">
  <input type="button" onclick="msg()" value="msg">
</center>

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

I encountered an issue while trying to build a website using React-static: the module 'perf_hooks' could not be found

Encountered an issue while trying to create a site with the react-static create command: Error: Cannot find module 'perf_hooks' at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Mod ...

"Eliminating Redundant JS and CSS Files in Magento to Improve

While analyzing the performance of a website, I noticed that GTmetrix found some CSS & JS files being loaded from different locations but containing the same file. An example: <action method="addItem" module="ves_blockbuilder" ifconfig="ves_blockbuilde ...

Implementing changes in the last loop iteration to impact the final result in Vue

Having recently delved into Vue, I'm having trouble figuring out how to solve this issue. Let me begin by showing you the code snippet followed by explaining the problem at hand. Currently, I am utilizing Vue-Good-Table for this project. methods:{ ...

JavaScript and Memory Allocation: Working with Array Elements

If I may ask a brief question driven by curiosity: imagine having an object with an array as a property, like this.arr = ["one", "two", "three", ...], and let's say this array is filled with n elements. What will occur to these elements if we execute ...

How can I utilize Javascript, HTML, JQuery, and CSS to dynamically set a variable based on a HTML Select's OnChange event, perform calculations, and automatically update the result?

I'm in the process of creating a pool pump calculator. While my HTML onchange function is working perfectly, I am struggling with passing the active Div value into my Javascript If Else statement and updating the outputs accordingly for each case of E ...

Build dynamic dropdown menus in Angular.js using cookie data

I'm facing an issue with populating a three-tier dependent dropdown in Angular with saved cookies. Sometimes, all three tiers populate correctly, but other times they show as blank strings or only partially populated. Upon inspecting the HTML code, I ...

chart for visualizing two rows with matching IDs and dates

I have been attempting to accomplish the following two scenarios: 1) When both ID and dates are the same in the chart, but the descriptions differ, I want to display them on separate lines. 2) If there is not enough room to show the row label, I would li ...

Arranging the local storage scores in increasing order

I am trying to organize the table data in ascending order, with the person having the highest score appearing at the top and the person with the lowest score at the bottom. I have been working on creating an array and using a for loop to sort the data ac ...

Is it possible to simultaneously wait for the completion of two methods instead of awaiting each one individually?

When dealing with 2 async methods, one may want to run them simultaneously but wait for both to finish before proceeding. Here is an example: exports.get = async id => { const part1 = await context.get(id); const part2 = await context.get2(id ...

Encountering a Django template extension issue: ValueError occurred while attempting to utilize i18n in a parent template

In my Django (4.1.2) project, I have a base.html template file structured as follows: <!DOCTYPE html> <html lang="en"> {% load static %} {% load i18n %} <head> <meta charset="utf-8"> {% block ...

How can I prevent the same JavaScript from loading twice in PHP, JavaScript, and HTML when using `<script>'?

Is there a PHP equivalent of require_once or include_once for JavaScript within the <script> tag? While I understand that <script> is part of HTML, I'm curious if such functionality exists in either PHP or HTML. I am looking to avoid load ...

How come the form fields keep getting cleared when you go back?

I am currently experiencing an issue with two forms on my website. One form is for initial registration (for members) and the other is for outsiders posting. Both forms lead to a confirmation page with error checking in PHP. However, I have noticed that if ...

Issue with AJAX form submission selecting an incorrect row among dynamically generated rows of data

Currently, I am fetching data from a database and displaying it in a table. One column includes the ID of each row, which I then pass to a modal using the following code snippet: <a href=".user_id<?php echo $row['id']; ?>" ...

The parameter 'Value | ValueXY' cannot be assigned to the type 'AnimatedValue<0>'

Recently, I delved into React Native documentation on Animations which can be found here: https://reactnative.dev/docs/animated After reading the docs, I decided to try out some code snippets: import {Animated as RNAnimated} from 'react-native' ...

Navigating through playlists on Ionic

Having just started exploring Ionic, I find myself in need of assistance with regards to navigation. I kicked off the project utilizing the sidemenus starter template which is a basic structure displaying items in a playlist using a playlist control. Howev ...

blocks that are not in the shape of a rectangle and have a background attachment

Having an issue with a v-shaped bottom as shown here. The goal is to trim the corners of the block while maintaining the fixed background (background-attachment: fixed) for scrollability and visibility through the v-bottom. Additionally, the angle must rem ...

In Angular 5, you can easily prevent interaction with a related button by disabling it when the corresponding reactive

I recently encountered a situation where I needed to implement a reactive form in a component. It looked something like this... form component.html <form [formGroup]="form" class="do-form"> <div formGroupName="dot"> <div class ...

Center the primary content on the screen when the header is present

I am struggling to vertically align the main content in the center of the screen. While I was able to achieve vertical alignment within a div, the presence of a header on the page is causing difficulty in centering the main content vertically with respect ...

The AddClass function does not work properly in the Kendo Tree View after the RemoveClass function, especially when selecting the same node

Hey there, I am currently working with a kendoTreeView and trying to set up an action triggered by clicking on the same selected node. To achieve this, I incorporated the following code in the change event: change : function(e) { $ ...

What is causing the malfunction of these three links?

Discover the yellow section below the images labeled "Read more about /college/" on . The first 3 links (Columbia, Princeton, and Brown) are not functioning properly, while the others are. An error in JavaScript is being raised stating Uncaught Error: Syn ...