Hamed Kamrava
Hamed Kamrava

Reputation: 12847

Change Element.attr when button clicked

My question is pretty like my last topic, but it's not the same.


I have several buttons and styled by CSS.

HTML codes is here :

<button class="Btn red">Btn1</button>
<button class="Btn blue">Btn2</button>
<button class="Btn green">Btn3</button>
<div id="Content"></div>

And CSS codes is here :

.red {
    background-color: #ff0000;
}
.blue {
    background-color: #0000ff;
}
.green {
    background-color: #00ff00;
}
#Content {
    background-color: #ccc;
    width: 150px;
    height: 150px;
} 

My question is :

How do i change (#Content).backgroundcolor to (Clicked_Btn).backgroundcolor using Javascript.

I have tried below JS commands, i think it has a lot of problems :

$(".Btn").click(function(){
document.getElementById("Content").style.backgroundColor = getComputedStyle(this).backgroundColor;    
);

DEMO in JsFiddle.


P.S :

As i mentioned above please don't suggest something like :

// HTML 

<button class="Btn red" onClick="changeColor(this);">Btn1</button>
...

//JavaScript

function changeColor(elem){
document.getElementById("Content").style.backgroundColor = getComputedStyle(elem).backgroundColor;    
}

I don't want to use onClick("function();") inside HTML button tags.

Any help would be awesome.

Upvotes: 0

Views: 439

Answers (2)

Mir
Mir

Reputation: 1613

if you are using $(".Btn").click then you are using jquery. This means that you can simplify a lot the subsequent line.

$(".Btn").click(function(){
  $("#Content").css('background-color',$(this).css('background-color'));   
});

and here is your fiddle edited: DEMO

Upvotes: 3

MrCode
MrCode

Reputation: 64526

Pure Javascript (no jQuery dependency):

var buttons = document.getElementsByTagName("button");
for(var i=0; i<buttons.length; i++){
    buttons[i].onclick = function(){
        document.getElementById("Content").style.backgroundColor = getComputedStyle(this).backgroundColor;
    }
}

Demo

Upvotes: 4

Related Questions