Is there a way to switch colors with the click of a button?

I'm looking to incorporate a bootstrap color picker into my website. I want the button inside this div to trigger the color chart and change the background color of the entire div when clicked. Can anyone help me achieve this functionality?

    <div class="row">
                <div class=" col-sm-4   border  border-primary  picker">
             <!--    add   a  button here -->
               <button class=" btn btn-primary"> select color </button>
                 <h4> color picker</h4>
                </div>
                <div class=" col-sm-8">
                </div>
           </div>
        </div>
        <script src="js/jquery-3.1.1.min.js"></script>
        <script src="src/colorPick.js"></script>
       <script>
            $(".picker").colorPick({
                'initialColor': 'onColorSelected',
                'palette': ["#1abc9c", "#16a085", "#2ecc71", "#27ae60", "#3498db", "#2980b9", "#9b59b6", "#8e44ad", "#34495e", "#2c3e50", "#f1c40f", "#f39c12", "#e67e22", "#d35400", "#e74c3c", "#c0392b", "#ecf0f1"],
                'onColorSelected': function() {
                    console.log("The user has selected the color: " + this.color)
                    this.element.css({
                        'backgroundColor': this.color
                    });
                }
            });
        </script>

Answer №1

To display the color chart, simply insert a button inside a div and trigger a click event on the button. Below is an example that you can use to achieve this. I hope this helps you out, my friend :))

<div class="row">
            <div class=" col-sm-4   border  border-primary  picker">
            <!--    add   a  button here -->
                <input type="button" id="btnShow" value="Choose color">
                <h4> colopicker</h4>
            </div>
            <div class=" col-sm-8">
            </div>
    </div>

$(document).ready(function(){

    $('#btnShow').on('click', function(){
        $(".picker").colorPick({
                'initialColor': 'onColorSelected',
                'palette': ["#1abc9c", "#16a085", "#2ecc71", "#27ae60", "#3498db", "#2980b9", "#9b59b6", "#8e44ad", "#34495e", "#2c3e50", "#f1c40f", "#f39c12", "#e67e22", "#d35400", "#e74c3c", "#c0392b", "#ecf0f1"],
                'onColorSelected': function() {
                    console.log("The user has selected the color: " + this.color)
                    this.element.css({
                        'backgroundColor': this.color
                    });
                }
            });
    });

});

Answer №2

Take a look at this - a live demonstration of your code in action

https://codepen.io/de-co/pen/xxxgKby

<script src="https://www.jqueryscript.net/demo/Flat-HTML5-Palette-Color-Picker-For-jQuery-colorPick-js/colorPick.js"></script>
<link href="https://www.jqueryscript.net/demo/Flat-HTML5-Palette-Color-Picker-For-jQuery-colorPick-js/colorPick.css" rel="stylesheet" type="text/css">
  <div class="row">
            <div class=" col-sm-4   border  border-primary  picker">
         <!--    add   a  button here -->
              <Button >colopicker</Button>
             <h4> colopicker</h4>
            </div>
            <div class=" col-sm-8">
            </div>
       </div>
    </div>

   <script>
     $('button').click(function(){

        $(".picker").colorPick({
            'initialColor': 'onColorSelected',
            'palette': ["#1abc9c", "#16a085", "#2ecc71", "#27ae60", "#3498db", "#2980b9", "#9b59b6", "#8e44ad", "#34495e", "#2c3e50", "#f1c40f", "#f39c12", "#e67e22", "#d35400", "#e74c3c", "#c0392b", "#ecf0f1"],
            'onColorSelected': function() {
                console.log("The user has selected the color: " + this.color)
               $('button').css({
                    'backgroundColor': this.color
                });
            }
        });
         });
    </script>

Answer №3

 <html>
   <head>
      <link rel="stylesheet" href="https://www.jqueryscript.net/demo/Flat-HTML5-Palette-Color-Picker-For-jQuery-colorPick-js/colorPick.css">
   </head>
   <body>
   <div class="row">
      <div class=" col-sm-4   border  border-primary ">
         <button class=" btn btn-primary picker"> clolor </button>
         <h4> colopicker</h4>
      </div>
      <div class=" col-sm-8 show_color">
        Show color
      </div>
   </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://www.jqueryscript.net/demo/Flat-HTML5-Palette-Color-Picker-For-jQuery-colorPick-js/colorPick.js"></script>
    <script>
    $( document ).ready(function() {
        $(".picker").colorPick({
            'initialColor': 'onColorSelected',
            'palette': ["#1abc9c", "#16a085", "#2ecc71", "#27ae60", "#3498db", "#2980b9", "#9b59b6", "#8e44ad", "#34495e", "#2c3e50", "#f1c40f", "#f39c12", "#e67e22", "#d35400", "#e74c3c", "#c0392b", "#ecf0f1"],
            'onColorSelected': function() {
                console.log("The user has selected the color: " + this.color);
                /*this.element.css({
                    'backgroundColor': this.color
                });*/
                $('.show_color').css('backgroundColor',this.color);
            }
        });
    });
    </script>
   </body>
</html>

I have integrated the document.ready method into the code and included the CSS link for the color palette, following the requirements of the colorpick.js plugin found at https://www.jqueryscript.net/other/Flat-HTML5-Palette-Color-Picker-For-jQuery-colorPick-js.html

The use of the ready() method ensures that a function is executed only after the document has fully loaded. Any JavaScript code placed within the $(document ).ready() method will be triggered once the page's DOM structure is prepared to run JavaScript.

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

Instructions on incorporating a logical condition for an object that is entering a region in motion

I am currently in the process of developing a new game concept. The goal of the game is to maneuver a square across the screen while avoiding raindrops that fall from the top of the canvas. I need assistance with programming the logic so that when a rain ...

Utilizing a combination of Mongo, Mongoose, Multer, and FS for deleting images

Looking at the code snippet below:- var Image = mongoose.model("Image", imageSchema); //Assuming all the configuration of packages are done app.delete("/element/:id", function(req, res) { Image.findByIdAndRemove(req.params.id, function(err) { if(e ...

Combine multiple arrays of JSON objects into a single array while ensuring no duplicates

Trying to combine two JSON arrays into one without duplicates based on date. The jQuery extend() function isn't doing the trick, so looking for an alternative solution that avoids nested $.each statements due to potential large dataset size... [ ...

A valid ReactComponent must be returned in order to properly render in React. Avoid returning undefined, an array, or any other invalid object

While working on my react application, I came across an error that I have been trying to troubleshoot without any success. It seems like I must be overlooking something important that could be quite obvious. *Error: VideoDetail.render(): A valid ReactComp ...

The changes made to $scope in AngularJS are not being displayed in the view

The View Section <div class="col-sm-8" data-ng-init="init_enable_disable()"> <select class="form-control" style="margin-top: 5px;" data-ng-model="schedule.scheduleType" data-ng-change="enable_disableDiv(schedule.scheduleType);"> ...

Creating a JSON Array from a PHP Array with json_encode()

I have used the built-in json_encode() function to encode an Array that I created. I am in need of formatting it into an Array of Arrays as shown below: { "status": "success", "data": [ { "Info": "A", "hasil": "AA" }, { " ...

Is there a way to send a JSON object and a file to an ASP.NET server using the fetch method?

I'm facing a challenge here, as I attempt to send a json object from my indexedDb along with an IFormFile object to the server at the same time. The method that handles this scenario is structured like so: [HttpPost] public async Task<IActionR ...

Using JQuery to create interactive dropdown menus with dynamic options

I am exploring the possibility of dynamically updating the choices available in an HTML dropdown menu based on the selection made by a user - consider this sample JSON data: series: [ {name: 'Company X', product: 'X1'}, {name: 'Co ...

The issue of duplicated elements arises when Ajax is utilized within Django

Upon form submission, a Graph is generated using Plotly. Utilizing Ajax to submit the form without refreshing the page results in duplicating the form div on the screen. How can this issue be resolved? The code snippet below showcases my implementation wit ...

Adjusting the transparency of each segment within a THREE.LineSegments object

I am following up on a question about passing a color array for segments to THREE.LineSegments, but I am looking for a solution that does not involve low-level shaders. I am not familiar with shaders at all, so I would prefer to avoid them if possible. I ...

Why isn't my content appearing correctly on different pages?

This ecommerce site is my very first project using React. I have created pages for Contact, Login, and more. The footer and other components display correctly on the home page, but when navigating to other pages, the content appears shortened. For referen ...

Encountered a 'Require() of ES Module' Error while Implementing Visx with Nextjs

Currently, I am utilizing the Visx library for chart creation within Nextjs. The scales provided by Visx are imported in this manner: import { scaleBand, scaleLinear, scaleOrdinal } from "@visx/scale" It is important to note that internally, Vi ...

What would be the ideal alternative if the Google Ajax API is unavailable, given that Google does not allow for local installation?

On my website, I include the following script: ... <script type="text/javascript" src="https://www.google.com/jsapi"></script> ... This particular script is from Google and is used to dynamically load other resources, such as the Google Chart ...

Firefox not responding to mouse movements

I am experimenting with creating an "animation" using JavaScript's "mousemove" Check it out here This is the code I am currently using $("body").mousemove(function(e){ var wWidth = $("body").width()/2 var wHeight = $("body").height()/2 var posX; v ...

Struggle with encoding dropdown menu options

I have multiple forms on my webpage and I want to be able to access them all at once and include them in a single large GET request. It's mostly working, but I'm encountering difficulties when dealing with drop down menus because their structure ...

Can someone explain to me the meaning of "var vm = $scope.vm = {}" in AngularJS?

While reading through the angularJS api, I came across some code that looked like this: myApp.controller('MyController', ['$scope', function($scope) { var vm = $scope.vm = {name:'savo'}; } ]); Initially, this mul ...

Ways to conceal the contents of an HTML element

I recently applied a background image to my "a" tag, but now I'm looking to hide only the HTML content within the tag. It's important that the background image and href address remain visible. Any suggestions on how to achieve this? Thank you in ...

Combining React with a jQuery plugin

Utilizing the jQuery nestable plugin in my React App has been a lifesaver for meeting my business needs. Despite being aware of the potential complications that arise from mixing jQuery with React, I couldn't find the exact functionality I required in ...

"Utilize Cypress to simulate clicking a button by triggering the enter key

Currently, I'm conducting testing on my application and attempting to trigger a button click using the Enter key: <v-btn class="submit-button" block color="primary" @click="login" > Log In < ...

Issues with routing on Zeit Now platform are causing a 404 NOT FOUND error when attempting to reload pages that are not the

Recently, I purchased a Next.js template from Themeforest and attempted to deploy it to Zeit Now. This particular project is set up as a monorepo using Lerna and Yarn workspace. The code for the Next.js app can be found inside the packages/landing folder. ...