To change the font color to red when clicked, I must create a button using HTML, CSS, and Javascript

Currently, I am utilizing CodePen to assess my skills in creating a website. Specifically, I am focusing on the HTML component. My goal is to change the font color to blue for the phrase "Today is a beautiful sunny day!"

Here is the snippet of code that I have developed so far:

<!DOCTYPE html>
<html>
  <head>
    <style>
      h1  {color: red; } 
      #redText {color: red } 
         </style>
     <title>your site</title> 
  </head>
   <body>
    <h1> Today's Weather Report</h1>
    <div class="redText">
    <p id="blueText"> Today is a beautiful sunny day!</p>
      
     <button type="button">Push</button> 
   
    <script>
     function changeColor(newColor){var elem = document.getElementById('blueText');
    elem.style.color = newColor;}
    <button onClick="changeColor(blue);">PUSH</button>
    </script>
   </body>
</html>

When looking at the current script I've written, it displays as follows:

Today's Weather Report (The font color should be red for this line and indeed it is.)

Today is a beautiful sunny day! (This sentence is expected to turn blue upon clicking the PUSH button, however, it remains black.)

At the bottom, you'll find a button labeled PUSH

Answer №1

avoid placing buttons within script tags :)

<!DOCTYPE html>
<html>
  <head>
    <style>
      h1  {color: red; } 
      #redText {color: red } 
         </style>
     <title>your site</title> 
  </head>
   <title>My Name Here</title> 
   </head> 
    
  <body>
    <h1> Today's Weather Report</h1>
    <div class="redText">
    <p id="blueText"> Today is a beautiful sunny day!</p>
    <button onClick="changeColor('blue');">PUSH</button>

   
    <script>
     function changeColor(newColor){
       var elem = document.getElementById('blueText');
       elem.style.color = newColor;
     }
    </script>
   </body>
</html>

Remember to enclose the color parameter in quotation marks since it's a string property!

Answer №2

To implement this change in the script, you need to take out the following code:

<button onClick="changeColor(blue);">PUSH</button>

Then, move the function call above into the html button tag.

<html>
  <head>
    <style>
      h1  {color: red; } 
      #redText {color: red } 
         </style>
     <title>your site</title> 
  </head>
   <title>My Name Here</title> 
   </head> 
    
  <body>
    <h1> Today's Weather Report</h1>
    <div class="redText">
    <p id="blueText"> Today is a beautiful sunny day!</p>
      
     <button type="button" onClick="changeColor('blue')">Push</button> 
   
    <script>
     function changeColor(newColor){
       var elem = document.getElementById('blueText');
       elem.style.color = newColor;
     }
    </script>
   </body>
</html>

Answer №3

It seems like the title is indicating a color change from blue to red, but there might be a missing word in there. Regardless, changing the text color can be easily accomplished in a few different ways as demonstrated below. Also, it looks like the DIV tag was not closed properly (<div class='redText'>), so I took it out of the snippet.

const clickhandler=function(e){
  let p=this.previousElementSibling;
  p.className=p.className=='blueText' ? 'redText' : 'blueText'
}
const togglehandler=function(e){
  this.previousElementSibling.classList.toggle('redText');
}

document.querySelector('button[name="bttn-1"]').addEventListener('click',clickhandler);
document.querySelector('button[name="bttn-2"]').addEventListener('click',togglehandler);
h1 { color:red } 
.redText { color:red!important; }
.blueText{ color:blue; }
<h1> Today's Weather Report</h1>

<p class="blueText"> Today is a beautiful sunny day!</p>
<button name='bttn-1' type="button">Push</button>

<p class="blueText">Today is also a beautiful hot and sunny day!</p>
<button name='bttn-2' type="button">Push-Toggle</button>

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'm curious about the origin and purpose of req.user - where does it come from and

Recently, I've been delving into Nestjs and found myself a bit puzzled by the req.user. Where does this come from and do we have to manually request it? What exactly is req.user and what advantages does it offer? Must I assign payload to it manually? ...

Error found in Paper.js at line 81: Uncaught TypeError - Unable to access properties of undefined (specifically '1') while utilizing Material UI and Joy UI

I am encountering an issue while using react js with material UI and JoyUI, where I am getting a blank screen. Below is the code snippet causing the problem: import React from 'react'; import { CssVarsProvider } from '@mui/joy/styles'; ...

Ways to exchange information among Vue components?

My role does not involve JavaScript development; instead, I focus on connecting the APIs I've created to front-end code written in Vue.js by a third party. Currently, I am struggling to determine the hierarchy between parent and child elements when ac ...

CSS might not always work properly on all web browsers, but it functions perfectly on Eclipse

When developing JSF pages with stylesheets, everything seems to be working fine in the Eclipse preview function. However, when I test the pages on IE8, the styles do not seem to have any effect. I am utilizing composite views to define a general layout fo ...

Setting the default selected option in Vue for an object

Can the v-model data be different from the default option in this scenario? data: function() { return { user: { usertype: {}, } } <select v-model="user.usertype" class="btn btn-secondary d-flex header-input"> <option v-for= ...

Guide to automatically sending users to a subdomain depending on their IP address location

Currently, my website is built using Node Express and I have a specific requirement. I want to redirect users to different subdomains based on their current location. For example, if a user in Singapore accesses site.com, they should be redirected to sg. ...

Implement a dialog on top of a current web page, achieve php-ajax query result, and enhance with

My website features 'dynamic' content, where 'static' nav-buttons replace specific div contents upon clicking. While I am able to retrieve my php/ajax results in a dialog box, I am struggling with placing this dialog above my current p ...

The click event fails to provide $event upon being clicked

Within my HTML structure in an angular 7 application, I have the following setup: My goal is to trigger the GetContent() function when any text inside the div is clicked. Strangely, when clicking on the actual text, $event captures "Liquidity" correctly. ...

A large canvas displaying a single optimized image

Hello, I have a large image on the canvas that measures around 10,000 pixels by 10,000 pixels. I am looking for zoom in/out functionality. Can you recommend what technology I should use? Should I consider splitting the image into smaller segments like Go ...

The event handler is not defined and is failing to recognize in the React context

Currently, as I delve into the realm of learning React, I find myself facing a perplexing issue regarding the mysterious undefined state of this event handler. Why is it behaving in such an enigmatic manner? const Login = () => { handleSubmit = (e) ...

There is no class present in the @Apply layer with Tailwind styling

I've been searching for what seems like a simple solution, but I can't seem to find it. While researching similar issues, I noticed that people were having problems with the Hover style and extra white space after it, which is not the issue in my ...

React Images: Carousel display issue with images not centered

Is there a way to center the selected image instead of it appearing on the left-hand side? Here is the current behavior: https://i.stack.imgur.com/SUWOK.jpg I am using the following packages in a sandbox environment with Next.js 11 and TailwindCSS 2.2.4: ...

Restrict the quantity of recommendations provided by the AutoComplete feature

After exploring the autocomplete API from https://material-ui.com/api/autocomplete/, I am unable to figure out a way, given my basic understanding of javascript, to restrict the display of a specific number of options beneath the TextField. I am working o ...

Starting the stored procedure/function using the sequelize.query() method

Below is the stored procedure I have written: CREATE OR REPLACE FUNCTION GetAllEmployee() RETURNS setof "Employees" AS $BODY$ BEGIN RETURN QUERY select * from "Employees"; END; $BODY$ LANGUAGE plpgsql; I am attempting to execute this stored procedure fro ...

Custom value in Field for radio type in Redux form

Can anyone help me figure out how to input text into a radio field using Redux form? Here are the fields I am working with: <Field name={some.name1} value={'text1'} component={renderRadioElement} type="radio" /> <Field name= ...

Changing time format from ISO time to short time in JavaScript

I am working on an ajax call that retrieves a time in the format 16:06:59, and I need to convert it to 4:06 PM. var mydate = obj[0].time; The variable mydate contains 16:06:59, but when I try to use it with var date = new Date(), it returns today's ...

Utilize Google Chrome Developer Tools to interact with the "Follow" buttons on the webpage by clicking on them

https://i.stack.imgur.com/W32te.png Here is the script I am currently using: document.querySelectorAll('.components-button components-button-size-mini components-button-type-orange desktop components-button-inline').forEach(btn => btn.click() ...

Utilizing cloud functions to distort an inappropriate image

I have a requirement to analyze any uploaded image for inappropriate content and blur it if necessary. The log this image is inappropriate indicates that the detection process is working correctly. However, I am not able to see any further logs which sugg ...

Turn off the background when the automatic popup box appears

I have implemented a popup box that automatically appears after 5 seconds when the site is loaded. However, if I click outside of the popup box, it closes. I want to disable the background when the popup box is displayed. If I remove the two lines of code ...

Various successful functions in Ajax

I am currently using an Ajax script to fetch data from my database and insert it into multiple textboxes. Along with posting the data, I also need to perform calculations using these textboxes. However, upon running the script, I noticed that all calculat ...