denniss
denniss

Reputation: 17589

Changing div background color when a link inside the div is clicked

So I have this button that is just actually a div and I have a link inside the div

<div id='button'>
    <a href='#'>Link</a>
</div>

I am able to use CSS to change the background color when the link is hovered over. However, how do I make the background color change when the link is clicked? I believe this requires some javascript? If so, can you guys help me with the java script? This is what I came up so far and yet it still does not work.

  <a href="/page/login" onmousedown="document.getElementById('button').backgroundColor='lavender'">login</a>

Upvotes: 1

Views: 4034

Answers (3)

sudipto
sudipto

Reputation: 2482

You can also try using :

<div id='button'>
    <a href='#' onmousedown="this.parentNode.style.backgroundColor='lavender';">Link</a>
</div>

Note that you can use the same code without modifying on any Anchor or other elements as it will be applied to whatever parent object is.

Upvotes: 2

Sascha Galley
Sascha Galley

Reputation: 16091

I would controll it with JavaScript and CSS. The following example will toggle the background color of the button with each click. This is done by adding the class clickedto the div, or remove it, if the div has already got this class.

the html code with inline javascript:

<div id="button">
    <a href="#" onmousedown="javascript:(btn=document.getElementById('button')).className = (btn.className  == 'clicked') ? '' : 'clicked';">Link</a>
</div>

the css:

#button {
    background-color: #ccc;
}

#button.clicked {
    background-Color: #123abc;
}

Upvotes: 1

patapizza
patapizza

Reputation: 2398

onmousedown="document.getElementById('button').style.backgroundColor='lavender'"

Upvotes: 1

Related Questions