Reputation: 662
I have a list of divs like this:
<div class="item">Click</div>
<div class="content">Hidden Content</div>
<div class="item">Click</div>
<div class="content">Hidden Content</div>
<div class="item">Click</div>
<div class="content">Hidden Content</div>
<div class="item">Click</div>
<div class="content">Hidden Content</div>
<div class="item">Click</div>
<div class="content">Hidden Content</div>
When the page is loaded the first div which has the id content is shown. What i would like to do is when i click on some other div (id="item") to hide the content of the previous clicked item and do some changes to the previous clicked div (id="item"). So far i've tried this:
$(document).ready(function(){
$(".item").first().css("border-right","none");
$(".item").click(function(e) {
$pressed = $(this);
if ($pressed.data("lastclick")){
$pressed.data("lastclick").css("border-right","solid");
$pressed.data("lastclick").css("border-right-width","1px");
$pressed.data("lastclick").find("span").remove();
}
$(this).next(".content").slideToggle(\'slow\', function() {
if ( $(this).is(":visible")) {
$pressed.css("border-right","none");
$pressed.append(\'<span style="float:right;font-weight:bold">\'+$(this).children().length+\'</span>\');
$pressed.data("lastclick",$pressed);
}
});});});
Upvotes: 1
Views: 13283
Reputation: 25224
Store the last clicked item in a simple JavaScript variable
var lastClicked;
$(".item").click(function(e) {
$(this). // Do your stuff to the clicked element here
// Then do what you will to the last-clicked element
// ...
// And finally assign the clicked element to the lastClicked variable
lastClicked = clicked;
}
A few helpful tips:
As mentioned in the comment, . is a class selector and # is an ID selector. You in your example were trying to select an element by ID using the class selector.
Where I have $(this)
you can chain operators. That is to say you can chain the CSS operators with the rest and have one single chained line of commands instead of repeating the selector (which is a performance waste).
You can use a "map" with the .css() command to apply multiple styles at once, like so:
.css({border-right: 'solid', border-right-width: '1px'})
... but as in your case you are simply modifying the border, you could (and should) simply do this:
border-right: 1px solid black;
Upvotes: 5
Reputation: 4024
You could simply your code by doing something close to this.
$('.item').click(function(){
$('.content').slideUp();
$(this).next('.content').slideDown()
})
Upvotes: 1