mzee99
mzee99

Reputation: 191

Show/hide text doesn't work when targeting link within div

Why does this work: http://jsfiddle.net/4q5du/

whereas this doesn't: http://jsfiddle.net/zcuYw/

The only thing I'm changing is that in the second one, I'm targeting a link within a div whereas in the first one, I'm targeting the link directly. Why isn't the second one working?

$('div.more').hide()
$('a.showmemore').click(function(){
    $(this).next('div').slideToggle()
})

vs

$('div.more').hide()
$('div.maurice a').click(function(){
    $(this).next('div').slideToggle()
})

Upvotes: 1

Views: 128

Answers (4)

Roko C. Buljan
Roko C. Buljan

Reputation: 206342

Click on $('div.maurice a') does not work cause next()

$(this).next('div').slideToggle();

in

<div class="maurice"> <a href="#">THIS</a>  NO ELEMENT HERE </div>
<div class="more">
    IT'S HERE!
</div>

does not exists

You should go one up (.parent() or .closest('div')) and than target the .next()

Upvotes: 0

iConnor
iConnor

Reputation: 20209

The reason it doesn't work.

you have this code

$('div.more').hide()
   $('div.maurice a').click(function(){
   $(this).next('div').slideToggle()
});

With this HTML

<div class="maurice"><a href="#">Hello</a></div>
<div class="more">
    Hey Ohhhh
</div>

And when you click on the a you want to slide toggle the next div element when there is no such thing, the next() function returns direct siblings, so in your case you need to go up one level with parent() and then use just next()

Result being

$('div.more').hide()
$('div.maurice a').click(function(){
   $(this).parent().next('div').slideToggle()
});

Demo: http://jsfiddle.net/zcuYw/1/

Upvotes: 2

DevlshOne
DevlshOne

Reputation: 8457

$('div.more').hide()
$('div.maurice a').click(function(e, ui) {
  e.preventDefault();
  $(this).parent().next('div').slideToggle()
})

You were shy one .parent().

Upvotes: 2

thecodeparadox
thecodeparadox

Reputation: 87073

$('div.more').hide()
$('div.maurice a').click(function (e) {
    e.preventDefault(); // As in your example, you're click on anchor so you
                        // you need to prevent default anchor behavior

    $(this)
       .parent()      // jump to .maurice
       .next('div')   // got next div 
       .slideToggle() // show effect
})

Upvotes: 3

Related Questions