Reputation: 141
I have a menu consisting of 4 div boxes. I want the active box to have a red border, if another box is clicked the border is white and the border of the other box is red. Do I need JavaScript or is CSS enough?
HTML
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
CSS
.box{
margin: 10px;
float: left;
width: 100px;
height: 50px;
background-color: blue;
border: solid 1px red;
}
Upvotes: 3
Views: 55818
Reputation: 1
You want to use the :focus
CSS pseudo-class in lieu of :active
.
Try this:
.box:focus {
border-color: red;
}
This should persist after the click event is completed.
Upvotes: 0
Reputation: 18855
For click you'll need JavaScript if you want to maintain the state, hover is OK with CSS.
You can use div:active { /* style */ }
for a click and hold style but it will disappear after mouse up.
This is a quick way to do it with jQuery:
$('.box').on('click', function(e){
e.preventDefault();
$(this).css('border-color', 'lime');
});
Probably better to toggle a class though:
JS:
$('.box').on('click', function(e){
e.preventDefault();
$(this).toggleClass('myClickState');
});
CSS:
.myClickState {
border-color: lime;
}
Upvotes: 7
Reputation: 71
function fnChangeBorder(boxId)
{document.getElementById(boxId).style.border = "solid #AA00FF";}
<div class="box" id="A" onclick="fnChangeBorder('A')">Click here !!</div>
i chose A as a parameter because numbers won't work as a function parameters
Upvotes: 3
Reputation: 2126
You can do this via jQuery (JSFiddle here):
$(document).ready(function() {
$('.box').click(function() {
if($('.active').length) {
$('.active').not($(this)).removeClass('active').addClass('box');
}
$(this).removeClass('box').addClass('active');
});
});
Upvotes: 0
Reputation: 1117
Take a look at this function:
It shows how to apply the click event and change the CSS class. You would simply have to create a desired class with border color.
Upvotes: 0
Reputation: 10772
Yes, you can use the :active
pseudo-selector to achieve this.
Try this:
.box:active {
border-color: red;
}
This, however, will not persist after you release the mouse.
It is also not supported in IE6.
Upvotes: 1