Reputation: 1611
I'm trying to make it so that when a div with an image is clicked both that div and it's related div (one with -content
) are appended with an .active
class (that is, when a image div is clicked it's respective content box pops-up)
http://jsfiddle.net/sergep/VM6AC/
I am unsure what I am doing wrong in the javascript section of the code:
$('.diagram div').click(function(){
var $this = $(this);
var type = $this.attr('class');
$this.siblings('.diagram div').removeClass('active');
$this.addClass('active');
$('div.diagram-content .' + type).addClass('active');
});
Why is it when I add a simple alert($this.attr('class'));
line the code stops working completely? (or does it?)
The html looks like so:
<div class="diagram">
<div id="gameboy" class="gameboy"></div>
<div class="switch"></div>
<div class="face"></div>
</div>
<div class="anatomy-content">
<div class="gameboy-content">This is a content box for the gameboy</div>
<div class="switch-content">This is a content box for the switch</div>
<div class="face-content">This is a content box for the face</div>
</div>
I decided to take the classes
approach as opposed to the data-type
approach.
Upvotes: 0
Views: 293
Reputation: 253416
I'd suggest:
$('.diagram div').click(function () {
var $this = $(this),
theClass = this.className;
$('.active').removeClass('active');
$this.add($('.' + theClass + '-content')).addClass('active');
});
Incidentally, using $this.attr('class')
doesn't fail (check the console), the problem is that you forgot to append the -content
string to that class-name:
$('.diagram div').click(function(){
var $this = $(this);
var theClass = $this.attr('class');
console.log($this,theClass);
$this.siblings('.diagram div').removeClass('active');
$this.addClass('active');
$('div.diagram-content .' + theClass + '-content').addClass('active');
// ^-- this is necessary, otherwise there's no match
});
References:
Upvotes: 1