Reputation: 2361
I have a problem with the below jQuery script:
$('span').click(function(){
var info = $(this).attr("rel");
var reference = this;
if ($(this).hasClass('listed')) {
// alert('follow');
$(".unlisted").addClass("unlisted-bw");
$(".special").addClass("special-bw");
}
if ($(this).hasClass('special')) {
// alert('follow');
$(".unlisted").addClass("unlisted-bw");
$(".listed").addClass("listed-bw");
}
if ($(this).hasClass('unlisted')) {
// alert('follow');
$(".listed").addClass("listed-bw");
$(".special").addClass("special-bw");
}
});
I want it to work in a way that if I click on one span (special
, listed
or unlisted
), The other spans to be inactive. How can I do this with jQuery ?
I created this script but not working correctly. http://jsfiddle.net/3nsrd/
Upvotes: 0
Views: 102
Reputation: 132
I've put together a quick and simple bit of javascript which will do what you need I believe:
$(document).ready(function() { //When the DOM is ready
$('span').on('click', function() {
$this = $(this);
if (!$this.hasClass("disabled")) {
$this.siblings().addClass("disabled");
}
});
});
Basically I add a class disabled to the siblings which can then be styled with:
.disabled {
background:#ccc;
cursor:default;
}
See it in action: http://jsfiddle.net/uBSX6/
Upvotes: 1
Reputation: 2001
You can select all of the other spans using .siblings()
. Here's an example:
$('span').click(function(e) {
$(this).removeClass('special-bw')
.siblings("span")
.addClass('special-bw');
});
DEMO http://jsfiddle.net/3nsrd/4/
This doesn't include adding their individual hover classes, which could be done by doing a $.each
on each of the siblings and using their title (or another attribute)
$('span').click(function(e) {
//get the name of the selected span
selectedSpan = $(this).attr("title");
//remove class of selected span -bw (i.e. special-bw);
$(this).removeClass(selectedSpan+'-bw')
.siblings("span").each(function(){
//foreach of the other spans, add their name + bw
$(this).addClass($(this).attr("title")+'-bw');
});
});
DEMO: http://jsfiddle.net/3nsrd/6/
Upvotes: 3
Reputation: 39540
I think this fiddle will suit your needs:
$('span').click(function(){
var parent = $(this).parent();
var classes = ['listed', 'special', 'unlisted'];
for (var i = 0; i < classes.length; i++) {
if ($(this).hasClass(classes[i])) {
for (var j = 0; j < classes.length; j++) {
if (classes[j] != classes[i]) {
$(parent).find('.' + classes[j]).addClass(classes[j] + '-bw');
}
}
$(this).removeClass(classes[i] + '-bw');
break;
}
}
});
or an even shorter version without a nested loop:
$('span').click(function(){
var parent = $(this).parent();
var classes = ['listed', 'special', 'unlisted'];
for (var i = 0; i < classes.length; i++) {
if ($(this).hasClass(classes[i])) {
$(parent).find(':not(.' + classes[i] + ')').each(function() {
$(this).addClass($(this).prop('class') + '-bw');
});
$(this).removeClass(classes[i] + '-bw');
break;
}
}
});
Upvotes: 0