teva
teva

Reputation: 117

Slide down div on click event

I have simple slide down script that shows div on click event. The problem i have is, that onclick event doesn't work if i have it wrapped in another div. If clickable div doesn't have any parent div it works fine.

I'm using this for multiple div's, where only one is opened at once.

I need open 1 to work

Here's Fiddle

HTML

<div>
  <div class="clickMore">open 1</div>
</div>

<div class="clickMore">open 2</div>
<div class="showMore" style="display:none;">
  <div>text</div>
</div>

JS

 $(function() {
  $('.clickMore').on('click', function() {
    $('.showMore').not($(this).next('.showMore')).slideUp('fast');
    $(this).next('.showMore').slideToggle('fast');
  });
});

Upvotes: 1

Views: 1165

Answers (3)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

Working fiddle.

The problem happen since you've two cases and the selector $(this).next('.showMore') will not return always the desired result, since when you've the .clickMore element inside a div the .next() function will not find the element because it's outside of the current div?

My suggestion id to add a condition to make sure if the related .showMore element is directly next to the clicked div or it should be targeted by adding the parent :

$(function() {
  $('.clickMore').on('click', function() {
    if ($(this).next('.showMore').length) {
      var show_more = $(this).next('.showMore');
    } else {
      var show_more = $(this).parent().next('.showMore');
    }

    $('.showMore').not(show_more).slideUp('fast');
    show_more.slideToggle('fast');
  });
});

Short version of condition could be :

$(function() {
  $('.clickMore').on('click', function() {
    var show_more = $(this).next('.showMore');
    show_more = show_more.length > 0 ? show_more : $(this).parent().next('.showMore');

    $('.showMore').not(show_more).slideUp('fast');
    show_more.slideToggle('fast');
  });
});

Upvotes: 1

Elyas Esna
Elyas Esna

Reputation: 635

Working Fiddle

$(function() {
  $('.clickMore').on('click', function() {   
    $('.showMore').hide();
    var el = $(".showMore");    
    $(".showMore").remove();
    $(this).append(el);
    $('.showMore').slideToggle();
  });
});

You are able to change the text content dynamically

Upvotes: 0

Gast&#243;n Corti
Gast&#243;n Corti

Reputation: 51

Try this

$(function() {
  $('.clickMore').on('click', function() {
    $('.showMore').slideToggle('fast');
  });
});

Upvotes: 0

Related Questions