Daniel Robinson
Daniel Robinson

Reputation: 653

change text on link when div is open

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?

Upvotes: 0

Views: 295

Answers (3)

Manoj Yadav
Manoj Yadav

Reputation: 6612

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');
    }
});

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

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");

Upvotes: 7

krishwader
krishwader

Reputation: 11381

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"
        });
    });
});

Upvotes: 1

Related Questions