Reputation: 530
I'm trying to add this the active class to the element when the user clicks it. Why does it not work? Is there something wrong with the syntax?
HTML code:
<div class="accordion">
<h3>a</h3>
<p class="active">b</p>
<h3>a</h3>
<p>b</p>
<h3>b</h3>
<p>b</p>
<h3>b</h3>
<p>b</p>
</div>
jQuery code:
jQuery(function($) {
$('div.accordion').click(function(e) {
e.preventDefault();
$(this).addClass("active");
});
});
What i wanna do is when the user clicks h3, thats when it sets the p tag below it the active class
Upvotes: 0
Views: 1165
Reputation: 193261
You need to bind click event to H3
elements. Also make sure you remove previously active elements:
var $h3 = $('.accordion > h3').click(function(e) {
e.preventDefault();
$h3.next('p').removeClass('active');
$(this).next('p').addClass('active');
});
Upvotes: 2
Reputation: 5752
change jQuery to like this
jQuery(function($) {
$('div.accordion p').click(function(e) {
e.preventDefault();
$(this).addClass("active");
});
});
jQuery(function($) {
$('div.accordion h3').click(function(e) {
e.preventDefault();
$(this).next().addClass("active");
});
});
Upvotes: 0
Reputation: 8380
I'm trying to add the active class to the p tag.
You forgot to add a click event to the p tag:
jQuery(function($) {
$('div.accordion h3').click(function(e) {
e.preventDefault();
$(this).next('p').addClass("active");
});
});
Upvotes: 1