I have one div with 4 spans in it:
<div id="text">
<span class="text_1" id="text1">text1 1</span>
<span class="text_2" id="text2">text2 2</span>
<span class="text_3" id="text3">text3 3</span>
<span class="text_4" id="text4">text4 4</span>
</div>
I have two buttons, buton1 that allows the class underline
.underline
{ border-bottom:1px solid #000; }
to be added to each span when i click each span (so if I click text1, then the other texts shouldn’t have an underline), and another button2 that should take off the underline until button1 is clicked again.
What I have is:
$('#button1').click(function () {
$(".text_1").click(function () {
$(".text_2").removeClass("underline");
$(".text_3").removeClass("underline");
$(".text_4").removeClass("underline");
$('.text_1').addClass("underline");
});
$(".text_2").click(function () {
$(".text_1").removeClass("underline");
$(".text_3").removeClass("underline");
$(".text_4").removeClass("underline");
$('.text_2').addClass("underline");
});
$(".text_3").click(function () {
$(".text_2").removeClass("underline");
$(".text_1").removeClass("underline");
$(".text_4").removeClass("underline");
$('.text_3').addClass("underline");
});
$(".text_4").click(function () {
$(".text_2").removeClass("underline");
$(".text_1").removeClass("underline");
$(".text_3").removeClass("underline");
$('.text_4').addClass("underline");
});
});
meaning all of the above would happen iff button1 is clicked.
so button2, I want it to remove all underline from everything, but I don’t want to have to do all of the above over again because eventually I’m going to have like 100 span tags!
What I thought was correct would be something like
$('#button2').click(function () {
$('#text').removeClass("underline") }); });
but that doesn’t work. (#text being the div id)
I then tried
$('#button2').click(function () {
$(".text_2").removeClass("underline");
$(".text_1").removeClass("underline");
$(".text_3").removeClass("underline");
$('.text_4').removeClass("underline");
I want it so that after you click button2, I cannot make the span text underline until I click button1. So the one directly above removes the underline class, but I can still click each span element and make it underline which I don’t want!
Could someone help me with this? I’m sort of new at this, so It’d be great if you could help me clean up button1’s functions too!!
Thank you!
You were almost there. Try the DEMO HERE
Update:
There is another solution also in which you can unbind the click event on span. But using a variable will be simple and faster. Consider unbinding if you can not create a global variable.