Reputation: 6259
Actually i have this jquery code:
$(function() {
$(".text").click(function() {
$("#Content").html($(this).next(".text1").html());
$(this).css( "color", "red" );
});
});
What i would like to change is that, only the recent clicked a-tag with the class "text" has his color changed to red. Or better said that when an a-tag with the class text is clicked the color red from the last clicked a-tag is removed! To summarize: Only one a tag should have the red color at the same time!
Upvotes: 0
Views: 113
Reputation: 253318
Assuming the a
elements are siblings, for example:
<a class="demo" href="#">link one</a>
<a class="demo" href="#">link two</a>
<a class="demo" href="#">link three</a>
<a class="demo" href="#">link four</a>
I'd suggest:
$(".demo").click(function () {
$(this).css('color', 'red').siblings().css('color','');
});
But rather than manipulate the CSS directly it's easier to take the same approach and apply/remove specific classes:
$(".demo").click(function () {
$(this).addClass('highlight').siblings().removeClass('highlight');
});
If they're not sibling elements, for example:
<ul>
<li><a class="demo" href="#">link one</a></li>
<li><a class="demo" href="#">link two</a></li>
<li><a class="demo" href="#">link three</a></li>
<li><a class="demo" href="#">link four</a></li>
</ul>
Then I'd suggest:
$(function () {
$(".demo").click(function () {
$('a.highlight').removeClass('highlight');
$(this).addClass('highlight');
});
});
References:
Upvotes: 2
Reputation: 7805
You can use this:
$(function () {
$(".text").click(function () {
$("#Content").html($(this).next(".text1").html());
$(".text").css("color", "");
$(this).css("color", "red");
});
});
Upvotes: 1
Reputation: 1959
Remove the color from all other nodes first, see comment below...
$(function() {
$(".text").click(function() {
$(".text").css("color",""); // remove the color from all other nodes first
$("#Content").html($(this).next(".text1").html());
$(this).css( "color", "red" );
});
});
Upvotes: 0
Reputation: 7352
There you go:
$(function() {
$(".text").click(function() {
$('.text').css('color','');
$(this).css( "color", "red" );
});
});
Upvotes: 1
Reputation: 135762
How about keeping the last clicked link in a variable?
$(function () {
var lastClicked;
$(".text").click(function () {
$("#Content").html($(this).next(".text1").html());
if (lastClicked != undefined) {
$(lastClicked).css("color", "");
}
lastClicked = this;
$(this).css("color", "yellow");
});
});
Check demo here. Of course, change the color from "yellow"
to "red"
(I used yellow because it calls more attention for the demo.
Upvotes: 1