Reputation: 11010
Here i am selecting a li item in a list and changing the border of that li item but if i select another li item the border of the currently selected item is changing but the previously selected li items border color has to change to the original color
Here is my code
$(document).ready(function () {
$("#list3 li").click(function () {
$("list3 li.clicked").removeClass("clicked");
$(this).addClass("clicked");
$(".clicked").css("border", "3px solid red");
});
});
Any suggestion?
Upvotes: 0
Views: 5358
Reputation: 92873
You can achieve this with less code. Write like this:
$("#list3 li").click(function () {
$("#list3 li").removeClass('clicked');
$(this).addClass('clicked');
});
Check this http://jsfiddle.net/q4qR8/1/
Upvotes: 1
Reputation: 13079
The line:
$(".clicked").css("border", "3px solid red");
Doesn't update the styling of "clicked" it only changes the styling of the selected element(s) i.e. $(this)
.
You'd be better adding a css rule for .clicked:
.clicked {
border: 3px soild red;
}
And removing the original line from your javascript thus:
$(document).ready(function () {
$("#list3 li").click(function () {
$("list3 li.clicked").removeClass("clicked");
$(this).addClass("clicked");
});
});
Then the styling changes will happen automatically using the addClass() and removeClass() functions.
Upvotes: 1
Reputation: 2004
This should work
$(document).ready(function () {
$("#list3 li").click(function () {
$("list3 li.clicked").css("border","0");
$("list3 li.clicked").removeClass("clicked");
$(this).addClass("clicked");
$(".clicked").css("border", "3px solid red");
});
});
Alternatively, you can put the border property in the .clicked class itself.
Upvotes: 1
Reputation: 5612
$(document).ready(function () {
$("#list3 li").click(function () {
$("#list3 li.clicked").toggleClass("clicked");
// if you don't want to be able to deselect the li that is already selected
// add this
// if (!$(this).hasClass("clicked")) {
$(this).toggleClass("clicked");
// }
});
});
and css style rule:
.clicked {
border: 3px solid red;
... extra customization
}
Upvotes: 1
Reputation: 5681
$(document).ready(function () {
$("#list3 li").click(function () {
$("#list3 li").css("border", "none");
$(this).css("border", "3px solid red");
});
});
Upvotes: 1
Reputation: 38345
Add a CSS definition for the class clicked
to the external CSS file for your page or inside a <style>
tag, like so:
.clicked {
border: 3px solid red;
}
That way the CSS handles the styling for you, and the border should automatically revert to its previous state once you remove the class.
Upvotes: 1