0

I have following html code where on clicking a particular button i want to change the color of a particular html element.

<paper-button style="background:blue" class="blue"></paper-button>
<paper-button style="background:red" class="red"></paper-button>

this is my script

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $(".blue, .red").click(function(){
            $(".abc").css("background-color", $(".blue, .red").css("background-color"));
        });
    });
    </script>

on clicking both the buttons the color of that element changes but changes to blue and doesn't change to red. When i change my code to

<paper-button style="background:red" class="red"></paper-button>
<paper-button style="background:blue" class="blue"></paper-button>

in this case the color changes to red irrespective of the button pressed. How to make sure that the color changes to the button pressed.

2
  • like this jsfiddle.net/bgm0ydmg Commented Sep 19, 2015 at 8:48
  • 1
    thanks for this but is there any way in which i give all my buttons same class and on clicking any of them the background of that particular element changes? Commented Sep 19, 2015 at 8:52

2 Answers 2

5

You are taking the background color of the 1st element in the dom, when you do this $(".blue, .red").css("background-color") . Take just the background color of the clicked element using $(this):

   $(".blue, .red").click(function(){
       $(".abc").css("background-color", $(this).css("background-color"));
   });
Sign up to request clarification or add additional context in comments.

Comments

0

Consider your HTML element whose background is to be changed is

<div class="abc"></div>

You can wrap your buttons in another div so that you don't have to bind each element to an onclick method and rather handle parent's onclick method.

<div id="colorSelectors">
  <span id="blue">Blue</span>
  <span id="red">Red</span>
  <span id="green">Green</span>
</div>

In javascript you can select your elements as follows.

const colorSelectors = document.querySelector('#colorSelectors');
const elementABC = document.querySelector('.abc');

Add event listener to the parent div.

colorSelectors.addEventListener('click', handleClick);

And handle the onclick function as follows

function handleClick(e) {
  elementABC.style.backgroundColor = e.target.id;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.