简体   繁体   中英

Multiple slidetoggle divs change text

I have this code which reveals a profile div onclick and also changes the text of the clicked element. There are multiple instances of this.

<div class="show" data-target=".open1">View Profile</div>
<div class="info open1">Lorem ipsum</div>

When another div is opened the previously open div closes. However, the text on this still remains as 'close profile'. I'd like to change this so the text changes back too.

Any idea how I can do this?

var $bgs = $('.info');
var $show = $('.show');

$($show).click(function () {
    var $target = $($(this).data('target')).stop(true).slideToggle();
    $bgs.not($target).filter(':visible').stop(true, true).slideUp();

    $(this).click(function(){
        $(this).text(function(_, oldText) {
            return oldText === 'Close Profile' ? 'View Profile' : 'Close Profile';

        });

    });
})

Please check this:

 var $bgs = $('.info'); var $show = $('.show'); $show.click(function () { var $target = $($(this).data('target')).stop(true).slideToggle(); var oldOpened = $bgs.not($target).filter(':visible'); oldOpened.stop(true, true).slideUp(); if(oldOpened.length > 0){ var tempClasses = $(oldOpened).attr("class"); var oldOpenClass = $.trim(tempClasses.replace("info","")); var oldOpenerDiv = $("div[data-target='."+oldOpenClass+"']"); $(oldOpenerDiv).text(function(_, oldText) { return oldText === 'Close Profile' ? 'View Profile' : 'Close Profile'; }); } $(this).text(function(_, oldText) { return oldText === 'Close Profile' ? 'View Profile' : 'Close Profile'; }); }) 
 .info{ display:none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div class="show" data-target=".open1">View Profile</div> <div class="info open1">Lorem ipsum 11</div> <div class="show" data-target=".open2">View Profile</div> <div class="info open2">Lorem ipsum 22</div> <div class="show" data-target=".open3">View Profile</div> <div class="info open3">Lorem ipsum 33</div> 

 var $bgs = $('.info'); var $show = $('.show'); $show.click(function() { var $target = $($(this).data('target')).stop(true).slideToggle(); $bgs.not($target).filter(':visible').stop(true, true).slideUp(); $(this).text(function(_, oldText) { return oldText === 'Close Profile' ? 'View Profile' : 'Close Profile'; }); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <div class="show" data-target=".open1">View Profile</div> <div class="info open1">Lorem ipsum</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM