0

I have a button on my page

 <button id="show1" class="morelinkblack">Find Out More</button>

When clicked it runs this code

 $("#show1").click(function(){
   $(".hidden-div1").slideToggle("slow");
 });

Is there a way of changing the text to say "Close" instead of "find out more" while the div is visible?

krishwader
  • 11,341
  • 1
  • 34
  • 51
Daniel Robinson
  • 643
  • 1
  • 10
  • 25

3 Answers3

7

You can do:

$("#show1").click(function(){
    var that = $(this);
    $(".hidden-div1").slideToggle("slow", function() {
        if ($(this).is(":visible")) {
            that.text("Close");
        } else {
            that.text("Find out more");
        }
    });
});

Based on the comments, the div could be opened or closed depending on where the user is directed from. A simple check in the DOM ready can set the text accordingly:

$(".hidden-div1").is(":visible") ? $("#show1").text("Close") : $("#show1").text("Find out more");
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • fantastic but when the page loads with the div open already it doesnt work properly. It starts with the find out more text – Daniel Robinson Jul 01 '13 at 15:16
  • If the default div is set to open, then set the default text to "Close" – tymeJV Jul 01 '13 at 15:18
  • it all depends on where they come from and what they are looking for. I need it to swing both ways. Thats why im finding it so hard I think. Yours is perfect until the page is loaded with the div open – Daniel Robinson Jul 01 '13 at 15:29
  • On page load, run a check, I'll update my answer to accomodate this. – tymeJV Jul 01 '13 at 15:29
  • thank you for your time you have saved my life there. Thought I was stuck forever!! Works like a dream!!!!!! – Daniel Robinson Jul 01 '13 at 15:34
1

Updated code

$("#show1").click(function() {
    var el = $(this);
    $(".hidden-div1").slideToggle("slow", function() {
        if ($(this).css('display') == 'none') { // <- Updated here to check if div is close or open
            el.text('Find Out More');
        } else {
            el.text('Hide More');
        }
    });
});

Update button text on document ready / page load

$(document).ready(function() {
    if ($(".hidden-div1").css('display') == 'none') {
        $("#show1").text('Find Out More');
    } else {
        $("#show1").text('Hide More');
    }
});
Manoj Yadav
  • 6,560
  • 1
  • 23
  • 21
1

Maybe this :

$("#show1").click(function () {
    var $div = $(this);
    $(".hidden-div1").slideToggle("slow").promise().done(function () {
        $div.text(function () {
            return $(this).is(":visible") ? "Close" : "Find Out More"
        });
    });
});
krishwader
  • 11,341
  • 1
  • 34
  • 51
  • thanks for the response. No that just loads with the find out more link still with find out more written. When clicked it shows the close link then doesn't change – Daniel Robinson Jul 01 '13 at 15:24