Question

I have some simple show/hide functionality written - whereby on a given page there are a few news items, and on page load they're in a "show less" state - and on clicking "more" they roll down to show the full article. here's my code.

$(".show-more").if($(".text").hasClass("show-more-height"));
$(".text").toggleClass("show-more-height");
$(".show-more").toggleClass("show-less");  
});

with my html looking more or less like this:

<div class="newsitem">
  <div class="text">a bunch of text</div>
  <div class="show-more">
    <span class="more">More</span>
    <span class="less">Less</span> 
  </div>
</div>

Essentially, it works fine - but if i have more than one newsitem on a page, the click event triggers all to show/hide. I'm guessing i need to target from the .newsitem and then use "this" - but i'm unsure how to do it.

Thanks in advance.

Was it helpful?

Solution

I believe you want $(this).find('.show-more') but you can approach this a little less javascripty.

Here is what I'm thinking:

$('.news-items').on('click', '.show-more,.show-less', function () {
  var $newsItem = $(this).closest('.news-item');
  $newsItem.toggleClass('expanded');
});

Then control the less and more display from css.

.news-item {
  border: 1px solid red;
  margin-bottom: 10px;
}
.news-item.expanded {
  height: 300px;
}

.show-less {
  display: none;
}

.expanded .show-more {
  display: none;
}

.expanded .show-less {
  display: block;
}

Here is a small demo: http://jsbin.com/bidawudu/3/edit?html,js,output

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top