What might be causing my button to require two clicks to toggle a function in JavaScript?

Need help with a button on my webpage! It's supposed to change colors from black to pink and then to purple when clicked. However, it's taking two clicks to go from black to pink. Can someone assist in fixing this issue so it changes color on the first click? Also open to suggestions for improvement.

HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Events Lab</title>
    <link rel="stylesheet" href="style.css">

</head>

<body>
    
        <h1 id="changeh1"> Clicking the button will change its color <h1>
        
        <button onclick="changeStyle()" type="button" name="button" id="buttonStyle">My color will change!</button>
    
<script src="script.js"></script>
    
</body>

</html>

JavaScript


function changeStyle() {


        //sets variable "button" to connect to HTML ID "buttonStyle"
        var button = document.getElementById("buttonStyle"),
            click = false;
            
        button.onclick = function() {
            click = !click;                                     
         
        //toggles background color back and forth between pink and purple when you click button
        button.style.background = click? "#ff0066": "#9933ff";  
         
        //toggles text back and forth between "I am now pink!" and "I am now purple!"
        document.getElementById('buttonStyle').innerHTML = click? 'I am now pink!': 'I am now purple!';
}
}


let buttonClick = document.getElementById('buttonStyle');
buttonClick.addEventListener('click', changeStyle);

CSS

body{
text-align: center;
font-family: Helvetica;
}


button {
width:350px;
height: 125px;
background-color: black;
color:white;
border: 5px solid black;
font-size: 20px;
}

Answer №1

Within your javascript code, you have created the following lines of code.

let buttonClick = document.getElementById('buttonStyle');
buttonClick.addEventListener('click', changeStyle);

Additionally, in your html file, you have included the following code snippet.

<button onclick="changeStyle()" type="button" name="button" id="buttonStyle">My color will change!</button>

Upon clicking the My color will change! button, the changeStyle function is triggered twice. This occurs because one event is defined within the html code and the other is defined in the javascript code. By removing the mentioned javascript code lines, the functionality will work as expected. Alternatively, you can eliminate the onclick event from the html code as shown below:

<button type="button" name="button" id="buttonStyle">My color will change!</button>

Answer №2

Two separate instances of event listeners were added - one in the HTML onclick attribute and another in Javascript using addEventListener.

To simplify the Javascript code, you can use the following:

var click = false;
let buttonClick = document.getElementById('buttonStyle');

function changeStyle() {
        click = !click;

        //Toggles background color between pink and purple
        buttonClick.style.background = click? "#ff0066": "#9933ff";  
         
        //Toggles text content between "I am now pink!" and "I am now purple!"
        buttonClick.innerHTML = click? 'I am now pink!': 'I am now purple!';
}
body{
text-align: center;
font-family: Helvetica;
}


button {
width:350px;
height: 125px;
background-color: black;
color:white;
border: 5px solid black;
font-size: 20px;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Events Lab</title>
    <link rel="stylesheet" href="style.css">

</head>

<body>
    
        <h1 id="changeh1"> Clicking the button will change its color <h1>
        
        <button onclick="changeStyle()" type="button" name="button" id="buttonStyle">My color will change!</button>
    
<script src="script.js"></script>
    
</body>

</html>

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

Parsing PHP array using JavaScript

$namesSelect = "SELECT username FROM users"; $names = mysql_query($namesSelect); $nameCheck = mysql_fetch_array($names) This code snippet retrieves all usernames from the users table and stores them in the $names array. I am now faced with the task of ...

How can I use jQuery to switch the positions of two <div> elements in HTML based on the selection of a dropdown value?

I need to switch the display positions of two <div> containers based on a dropdown value change. Can this be accomplished using jQuery? Here are the two div containers whose display positions need to be interchanged: <div id="first"><p> ...

Monitoring the bandwidth usage of your meteor.js server?

After successfully measuring the bandwidth of a "basic node.js server" with this clever method, I'm intrigued about how to replicate the process on a meteor instance. Any insights on how to proceed? ...

Utilizing replace and regex in jQuery to add a space before a capitalized character within a word

these are the elements in the array WorkNumber WorkType Version Status Module Priority AssignedBy AssignedTo Subject Details EstimatedTime ActualTime CreatedDate ModifiedDate i would like the ou ...

Is it possible to center Div/Img elements both vertically and horizontally over a background of a cover size?

^Read my jsfiddle link^ I have a small jq script that adjusts background image size based on viewport dimensions. My issue is with a div (.png) that needs to be centered vertically and horizontally on the background, no matter the screen size. I've t ...

The basic CSS container fails to properly align its elements as intended

Recently, I created a CSS div using Bootstrap and added some custom styling. You can check out the fiddle for a live demo of the code: https://jsfiddle.net/w9gyc0t5/. Here's the actual code: <!-- Bootstrap docs: https://getbootstrap.com/docs -- ...

What is the method to choose an invisible link without an identifier using Selenium WebDriver?

I am attempting to click on the link labeled 'User Requested'. This link only appears when hovering over the menu. This is the HTML code: <ul class="k-widget k-reset k-header k-menu k-menu-horizontal" id="menu" data-role="menu" tabindex="0" ...

Creating a redirect page without triggering a preventDefault() function:

One issue arises when I include e.preventDefault and it doesn't redirect to homeadmin.php after a successful login, even though the ajax call is successful and there are no validation errors. The second problem is that in order to display error messa ...

I wish for the value of one input field to always mirror the value of another input field

There is a checkbox available for selecting the billing address to be the same as the mailing address. If the checkbox is checked, both values will remain the same, even if one of them is changed. Currently, I have successfully achieved copying the mailing ...

RxJs will only consider the initial occurrence of a specific type of value and ignore any subsequent occurrences until a different type of value is encountered

I'm faced with a situation where I need to extract the first occurrence of a specific value type, followed by the next unique value of a different type. Let's break it down with an example: of(1,1,1,1,2,3,4) .pipe( // some operators ) .subsc ...

Is there a way to show a specific div element only during the initial two occurrences of a jade each loop?

How can I display a specific div only during the first two iterations of a loop in Jade? Is there a way to achieve the following logic in Jade? counter = 0 for each tab in tabs if (counter == 0) div.nav-header NAVIGATION counter++ else if ( ...

Deactivate button using Javascript

Can anyone assist me with this issue I am having? I currently have a button set up as follows: <input type="button" id="myButton" name="myButton" value="ClickMe!!" onClick="callMe()"/> I need to disable the button using jQuery, standard javascript ...

"Encountering a JavaScript Issue While Displaying an iFrame

Having trouble displaying an iframe on a ColdFusion website when passing values in the URL. A similar method worked fine on a non-ColdFusion site, so I suspect the issue is with ColdFusion itself. Unfortunately, I have no experience with ColdFusion. If I ...

Is there a solution for the issue where the :after pseudo-element on a TD in IE9 does not accurately reflect the TD height?

In the design I'm currently working on, there is a requirement for a border around a table row. Due to certain complications, using the border property directly is not an option. In trying to find a solution, I have experimented with two different app ...

Two Ajax Requests Simultaneously

I am currently faced with the challenge of handling two requests simultaneously. The first request involves executing a lengthy PHP script that takes 10 minutes to complete (I cannot modify it using JavaScript, so that's not an option). The second ...

In the process of managing various API requests through a Node/Express middleware API, experimenting with the implementation of promise.all()

As I navigate through this project, I am stumbling upon various gaps in my knowledge. My current task involves constructing an intermediate API server. Some of the endpoints require processing an array of information, initiating external calls for each pie ...

Tips for integrating Tornado authentication with AngularJS

I have been experimenting with the authentication system outlined in the tornado documentation, and I am encountering a Cross-Origin Request issue when trying to integrate it with AngularJS. Is there a way to successfully combine Tornado's authentica ...

Encountering a blank screen on the Swagger route in ExpressJs: How to troubleshoot

I have set up swagger-ui-express with swagger-jsdoc in my Express.js project following various tutorials and official documentation. However, despite implementing everything correctly, I am facing an issue where the Swagger URL displays a blank white scree ...

Struggling to set up an HTTPS server with Express and Node.js - it just won't start

I'm attempting to configure HTTPS with express.js for node, but I am encountering issues getting it to work. Below is the code from my server.js file: const fs = require('fs'); const http = require ('http'); const https = require( ...

Distinct elements within a JavaScript hash

Is there a jQuery method to add a hash into an array only if it is not already present? var someArray = [ {field_1 : "someValue_1", field_2 : "someValue_2"}, {field_1 : "someValue_3", field_2 : "someValue_4"}, {field_1 : "someValue ...