Sam Pettersson
Sam Pettersson

Reputation: 17

JQuery one function for several buttons

Im having quite a trouble finding words for this problem i have stumbled across.

Well, i have a link (normal a href) what i want that to do is on click i want a div to be shown which has the class of .more. Though i will have this in an ul so i need this function to work on several links all displaying the second div in an li with class .more.

This is the HTML markup, i'll hope you understand my question.

Thank you!

<li>
<div class="less">
<h1>Title</h1>
<p>12:00 - 13:00</p>
<a class="show_more" href="">Show more</a>
</div>
<div class="more" id="more_">
<p class="text">text</p>
<p class="place">Room / <a href="" class="address">An address</a></p>
<a class="show_less" href="">Show less</a>
</div>
</li>

Upvotes: 0

Views: 112

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 185913

$wrapper.on('click', 'a.show_more', function (e) {
    e.preventDefault();
    $(this).closest('li').find('.more').show();
});

where $wrapper is a jQuery object referencing the wrapper element of your thing, e.g. the UL element in this case.

Upvotes: 2

adeneo
adeneo

Reputation: 318182

A href shouldn't be empty, so you should add # to the href, and then target the anchor, find the .less element, and the next .more element would be the one to show.
When clicking the .show_less button it would be the closest .more element you're going to hide :

$('.show_more').on('click', function(e) {
    e.preventDefault();
    $(this).closest('.less').next('.more').show();
});

$('.show_less').on('click', function(e) {
    e.preventDefault();
    $(this).closest('.more').hide();
});

Upvotes: 2

Related Questions