Reputation: 861
I have two buttons on my website, they should show content when someone clicks on the button. But instead of showing content, the button takes me back to the top of the page.
jQuery Code
/********************
* Enable Vacature Dropdown
* *****************/
var vacatureClickHandler = $(function(){
$(".vacatures li").on("click", "a", function(event){
if(event.target.attr('id') == 'link-0'){
$('#content-0').toggleClass('active').fadeToggle();
event.preventDefault();
} else if(event.target.attr('id') == 'link-1'){
$('#content-1').toggleClass('active').fadeToggle();
event.preventDefault();
}
});
});
$(".vacatures li").on("click", "a", vacatureClickHandler);
HTML for the jQuery
<div class="section vacatures">
<h2>VACATURES</h2>
<h3>OP ZOEK NAAR NIEUWE <span>COLLEGA's</span></h3>
<ul>
<li>
<a id="link-0" href=""><span>OPEN SOLLICITATIE</span><span><img src="../../img/arrow_down.png"</span></a>
<p id="content-0">Blablabla</p>
</li>
<li>
<a id="link-1" href=""><span class="strike">ALLROUND DESIGNER</span><span class="hired">HIRED!</span><span><img src="../../img/arrow_down.png"/></span></a>
<p id="content-1">Blablabla</p>
</li>
</ul>
</div>
Here's the jsFiddle, what it has to do: someone clicks on the dropdown button and then the content shows.
Upvotes: 2
Views: 830
Reputation: 1484
If you just have one sibling next to the link you don't need the id's, don't need to "switch" and can use the siblings() method. See this (jsfiddle below):
JS
$('ul.nav > li > a').on('click', function(e){
e.preventDefault()
$(this).siblings().slideToggle();
})
CSS
.content {
display:none;
}
HTML
<div class="section vacatures">
<h2>VACATURES</h2>
<h3>OP ZOEK NAAR NIEUWE <span>COLLEGA's</span></h3>
<ul class="nav">
<li>
<a href="/"><span>OPEN SOLLICITATIE</span></a>
<p class="content">Blablabla</p>
</li>
<li>
<a href="/"><span class="strike">ALLROUND DESIGNER</span></a>
<p class="content">Blablabla</p>
</li>
</ul>
</div>
http://jsfiddle.net/josfaber/W835D/
Upvotes: 0
Reputation: 38102
1) You're forgot to include jQuery in jsFiddle
2) Place event.preventDefault();
outside of your if else
condition
3) Use this.id
instead of event.target.attr('id')
Final code for your click function look like:
$(".vacatures li").on("click", "a", function (event) {
event.preventDefault();
if (this.id == 'link-0') {
$('#content-0').toggleClass('active').fadeToggle();
} else if (this.id == 'link-1') {
$('#content-1').toggleClass('active').fadeToggle();
}
});
Upvotes: 3