inaz
inaz

Reputation: 1785

Height change to auto works for all elements

This code changes the height of a div to auto when I click the "more+" button.

How can I run this function only for the div that I want?

Currently it works for all the divs when I click on the "viwviewmori" button.

Another issue is when I click the "viwviewmori" button for the second time, I want to change the text "... less -" to "more" again.

<!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    </head>
    <body>
    <div class="hidi">
    <div class="uner-sch">
    <input type="checkbox"/>
    first
    </div>
    </div>
    <div class="viwviewmori"> ... more +</div>
    <div class="hidi">
    <div class="uner-sch">
    <input type="checkbox"/>
    second
    </div>
    </div>
    <div class="viwviewmori"> ... more +</div>


    <script>
    $(".viwviewmori").click(function(){
    var el = $('.hidi'),
        curHeight = el.height(),
        autoHeight = el.css('height', 'auto').height();
    el.height(curHeight).animate({height: autoHeight}, 1000),
              $(this).text('... less -');
    });
    </script> 
    </body>
    </html>

Upvotes: 0

Views: 77

Answers (2)

gaetanoM
gaetanoM

Reputation: 42054

The click handler function takes as argument an event Object.

So, you may use event.target.

For the text to be changed you can use:

 el.text( (el.text().indexOf('more')> -1) ? '... less -' : '... more +');

$(function () {
  $(".viwviewmori").click(function (e) {
    var el = $(e.target),
        hidi = el.prev('div.hidi'),
        curHeight = hidi.height(),
        autoHeight = hidi.css('height', 'auto').height() * ((el.text().indexOf('more') > -1) ? 3 : 1);
    hidi.height(curHeight).animate({height: autoHeight}, 1000),
      el.text(((el.text().indexOf('more') > -1) ? el.text().replace(/more \+$/g, 'less -') : el.text().replace(/less \-$/g, 'more +')));
  });
});
.viwviewmori {
  width: 30%;
  border:1px solid black;
}
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>

 <div class="hidi">
    <div class="uner-sch">
        <input type="checkbox"/>
        first
    </div>
</div>
<div class="viwviewmori"> ... more +</div>
<div class="hidi">
    <div class="uner-sch">
        <input type="checkbox"/>
        second
    </div>
</div>
<div class="viwviewmori"> ... more +</div>

Upvotes: 2

Peter Wilson
Peter Wilson

Reputation: 4319

You can change it to be:

 var el = $(this).find('.hidi');

This will let you select only .hidi inside the clicked div.

Upvotes: 0

Related Questions