Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery toggle next P

Im trying to create a function that will toggle a paragraphs display CSS when a button is clicked only i cant seem to get it to work at all, My browser just goes back to the top of the page? My jQuery is...

$('.useful-links ul li a').click(function(){
    $('.useful-links ul li a').parent('li').find('p').toggle();     
});

and my markup is

<li>
     <a href="#">RESIDENTIAL AGENTS</a>
     <p style="display:none;">sfsdfsdfsd</p>
</li>
like image 759
Liam Avatar asked Mar 12 '26 00:03

Liam


2 Answers

I'm assuming your HTML structure is like this:

<div class="useful-links">
    <ul>
        <li>
            <a href="#">RESIDENTIAL AGENTS</a>
            <p style="display:none;">sfsdfsdfsd</p>
        </li>
    </ul>
</div>​

// For your jQuery selector to work as you have it

$('.useful-links ul li a').on('click', function (e) {
    e.preventDefault(); // stop href()
    $(this).next('p').toggle();     
});

Demo: http://jsfiddle.net/p4SJB/

like image 79
Mark Pieszak - Trilon.io Avatar answered Mar 14 '26 12:03

Mark Pieszak - Trilon.io


Use $(this):

$('.useful-links ul li a').click(function(e){
    e.preventDefault();
    $(this).parent('li').find('p').toggle();     
});

I prefer to find the common parent, then "find" the target element. This means that if your HTML markup changes so that p comes before a, your jQuery won't be affected.

See Demo: http://jsfiddle.net/S2hSp/

like image 43
Curtis Avatar answered Mar 14 '26 12:03

Curtis