Modify the background color when clicking by offering various color options to choose from using jQuery

I need assistance with adding multiple color choices using HTML and CSS. I am having trouble implementing this feature in my code. Below are the snippets of my code:

$(document).ready(function() {
      $('#btn').click(function() {
        $('body').css('background', '#ff0000', '#80ff33');
      });
body {
  height: ;
  background: #D8D8D8;
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

#btn {
  margin-left: 550px;
  width: 200px;
  height: 100px;
  font-size: 2em;
  border-radius: 10px;
  background: #ffffff;
}

#btn:hover {
  background: #ff0000;
  background: #80ff33;
  color: #ffffff;
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<section class="text">
  CLICK THE BUTTON TO<br> CHANGE THE BACKGROUND!
</section>
<button id="btn">CLICK ME!</button>

Answer №1

It appears that you forgot to properly close your function in the code snippet below:

$(document).ready(function() {
  $('#btn').click(function() {
    $('body').css('background', '#ff0000', '#80ff33');
  });
});

Here is a demo:

$(document).ready(function() {
  $('#btn').click(function() {
    $('body').css('background', '#ff0000', '#80ff33');

  });

});
body {
    height: ;
    background: #D8D8D8;
}

.text {
    color: #686868; 
    font-family: arial;
    font-size: 2em;
    text-align: center;
    margin-top: 50px;
    margin-bottom: 20px;
}

#btn {
    margin-left: 550px;
    width: 200px;
    height: 100px;
    font-size: 2em;
    border-radius: 10px;
    background: #ffffff;
}

#btn:hover {
    background: #ff0000;
    background: #80ff33 ;
    color: #ffffff;
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<section class="text">
  CLICK THE BUTTON TO<br> CHANGE THE BACKGROUND!
</section>
<button id="btn">CLICK ME!</button>


You have various methods at your disposal, one of which involves updating a CSS custom property.

For example, using a data-attribute, you can easily add multiple button colors as shown below:

  • Javascript version:

DEMO or see the snippet provided below:

for (let e of document.querySelectorAll("button")) {
  cust = e.dataset.bgcolor;
  e.style.background = cust;
  e.textContent = cust;
  e.addEventListener("click", function() {
    cust = e.dataset.bgcolor;
    document.documentElement.style.setProperty("--bgColor", cust);

  });
}
html {
  background: #D8D8D8;
}

body {
  margin: 0;
  height: 100vh;
  background: var(--bgColor);
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

.grid {
  display: grid;
  width: 200px;
  grid-template-columns: repeat(2, 1fr);
  margin: auto;
}
<section class="text">
  CLICK THE BUTTON TO<br> CHANGE THE BACKGROUND!
</section>
<div class="grid">
  <button data-bgcolor="orange">bgcolor:</button>
  <button data-bgcolor="white">bgcolor:</button>
  <button data-bgcolor="lightblue">bgcolor:</button>
  <button data-bgcolor="lightgreen">bgcolor:</button>
  <button data-bgcolor="brown">bgcolor:</button>

  • Equivalent JQuery snippet :

$("button").each(function() {
  bg = $(this).data("bgcolor");
  $(this).css("background", bg);
  $(this).html(bg);
  $(this).click(function() {
    bg = $(this).data("bgcolor");
    $("html").css("--bgColor", bg);
  });
});
html {
  background: #D8D8D8;
}

body {
  margin: 0;
  height: 100vh;
  background: var(--bgColor);
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

.grid {
  display: grid;
  width: 200px;
  grid-template-columns: repeat(2, 1fr);
  margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="text">
  CLICK THE BUTTON TO<br> CHANGE THE BACKGROUND!
</section>
<div class="grid">
  <button data-bgcolor="orange">bgcolor:</button>
  <button data-bgcolor="white">bgcolor:</button>
  <button data-bgcolor="lightblue">bgcolor:</button>
  <button data-bgcolor="lightgreen">bgcolor:</button>
  <button data-bgcolor="brown">bgcolor:</button>

Answer №2

by clicking the button, you have the power to transform the background color

body {
    height: ;
    background: #D8D8D8;
}

.text {
    color: #686868; 
    font-family: arial;
    font-size: 2em;
    text-align: center;
    margin-top: 50px;
    margin-bottom: 20px;
}

#btn {
    margin-left: 550px;
    width: 200px;
    height: 100px;
    font-size: 2em;
    border-radius: 10px;
    background: #ffffff;
}

#btn:hover {
    background: #ff0000;
    background: #80ff33 ;
    color: #ffffff;
}
</script>
<section class="text">
  CLICK THE BUTTON TO<br> CHANGE THE BACKGROUND!
</section>
<button id="btn" onclick="document.body.style.backgroundColor = 'green';">Click Me</button>

Answer №3

$(document).ready(function() {
      $('#btn').click(function() {
        $('body').css('background', '#ff0000', '#80ff33');
      });
});
body {
  height: ;
  background: #D8D8D8;
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

#btn {
  margin-left: 550px;
  width: 200px;
  height: 100px;
  font-size: 2em;
  border-radius: 10px;
  background: #ffffff;
}

#btn:hover {
  background: #ff0000;
  background: #80ff33;
  color: #ffffff;
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<section class="text">
  CLICK THE BUTTON TO<br> ALTER THE BACKGROUND!
</section>
<button id="btn">CLICK ME!</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

What is the best way to prevent the click event of a container div from triggering when clicking on elements within the container using JQuery

For example: <div class="wrapper"> <div class="inner">Clicking me won't trigger the wrapper click event</div> </div> $('.wrapper').click(function(){ // Do something with the wrapper here }); However, when I cli ...

Having trouble with drop down modification in Firefox

I have encountered an issue with my code that is designed to modify 2 drop down menus on page load and selection. The first menu should adjust based on the main categories related to the page category upon loading the page. The second menu offers different ...

Use CSS media queries to swap out the map for an embedded image

Looking to make a change on my index page - swapping out a long Google Map for an embedded image version on mobile. The map displays fine on desktop, but on mobile it's too lengthy and makes scrolling difficult. I already adjusted the JS setting to "s ...

I'm having some trouble with jQuery's GET function while working with CodeIgniter. Instead of retrieving a single value, it seems to be returning the source code for a

I have been experimenting with the jQuery GET method, but the results are not what I expected. My goal is to call a function from my controller using jQuery and display the returned value in a specific div within my view. Below you can see the code snippet ...

What is the best way to use PHP to call an ACF variable and substitute a nested HTML element?

Utilizing the repeater field in Wordpress' advanced custom fields, I have made the content on my site dynamic. View an image of the static markup here The following is how I structured the content using plain HTML: <div class="container" ...

`Changing the iframe content dynamically with next and previous buttons: a step-by-step guide`

function displayPDF(fileSlNo){ var data = { pageMode: "PDF_DISPLAY", fileSlno: fileSlNo }; var d = $.param(data); var request = $ .ajax({ type: "GET", url:"folderNavigation.do?"+d, dataType : "TEXT", success: functio ...

fetching the name of the button from a servlet on a JSP page

I am currently working on a project in eclipse using JSP. I am facing an issue with detecting which button is pressed when submitting a form with an ajax call. The request.getParameter(button-name) method is returning null within the doPost method of the s ...

A problem with Internet Explorer 8 when using jQuery slide animations

Hey there! Check out this link for the issue.. Here's what it says: SCRIPT5007: 'toLowerCase' Unable to get value of property: the object is empty or undefined..jquery.slider.min.js, line 398.. I'm not familiar with jquery. Any sugg ...

PHP - Utilize get_option to send styling options to style.php

I'm having trouble figuring out how to structure my question, but in my plugin folder I have 2 files: 1 - "index.php" add_action( 'wp_enqueue_scripts', 'register_plugin_styles' ); function my_admin_setting() { include(' ...

ways to view a user's profile through a search query or by clicking on their profile link

Here, I have created a hyperlink to the customer. <a name="id" href="https://127.0.0.1/newtaxicab/account/driver/profile/index.php?id=<?php echo $data['id']; ?>"><?php echo $data['fullname']; ?></a> The content ...

Tips for incorporating an image into the background of a mobile device

My attempt to set an image as a background was successful on desktop, but unfortunately, it doesn't work on my phone. I have specified 'cover' as the background-size, expecting it to cover all the space on mobile as well. Here is the code s ...

Whenever I change the value of a textbox using plain JavaScript, the text becomes hidden from view

I'm struggling to understand why this function is making the textbox value invisible. I attempted changing the hidden field to a visible field, but that didn't solve the issue. Would appreciate some guidance. Here's the complete page code, p ...

Is there a way to customize the design of an HTML scrollbar to resemble the one often seen on Google search engine result pages

While casually browsing online, I stumbled upon something truly unique. The image below shows a Google search result in Firefox that I have never encountered before or since. This screenshot captured a search result that was scrollable within itself. Isn& ...

Having trouble with CSS hover sliding animation going from top to bottom not activating

I'm trying to create a social hover effect where the background color slides down from top to bottom. I've written the CSS code for it, but for some reason, it's not working as expected. ul.socials { display: flex; flex-direction: row ...

Exploring the concept of Javascript Objects and the undefined value

I've encountered an issue with a Wordpress plugin that is no longer supported. After some investigation, I have identified the problem area in the code: i[C][0]; The above line seems to be causing an 'undefined' return within the function ...

Different ways to pause and restart slides.jquery.js

UPDATE July 4: I am still facing difficulties with this problem. It seems that creating a function to stop the slideshow based on the 'playing' class might solve it, but I am unsure how to implement such a function. I am utilizing slides.js on a ...

Adjusting the decimal points of numbers within a table to create the illusion of a "centered" alignment within the cell

Looking for a table design featuring a column of decimal numbers, each with varying lengths before and after the decimal point, while keeping the decimal points aligned. The width of the column should be flexible, expanding to accommodate long numbers in ...

The Facebook like button may fail to appear if the href contains a dynamic component in an asp.net framework

Currently, I am facing a problem with my asp.net page that has a repeater list containing Facebook like buttons. The issue arises when I try to add different query string components to the href of each like button within the repeater items. In such cases, ...

The button event is currently only targeting the initial class. (Jquery)

I am having an issue where only the first instance of the saveBtn class is being saved into local storage when clicked. Can anyone provide some assistance with this? Here is the HTML: <div class="hour-container" id="8am"> & ...

Retrieve the information sent back by AngularJS and pass it to a JavaScript function

I am working on a form using AngularJS to create a new object, which is returned as "marker." $scope.createMarker = function() { $http.post('/markers/create', $scope.marker) .success(function(data) { }) .error(funct ...