Changing text on click with jquery

Hi all, could someone tell me how to change the text of a link when its clicked?

I use this code as a show/hide

<script type="text/javascript">
$(document).ready(function() {
 // hides the slickbox as soon as the DOM is ready
 // (a little sooner than page load)
  $('#slickbox').hide();

  // toggles the slickbox on clicking the noted link
  $('a#slickbox-toggle').click(function() {
    $('#slickbox').slideToggle(400);
    return false;
  });
});
</script>

And this is the markup…

<a id="slickbox-toggle" href="#">Show box</a>			

<div id="slickbox">Content goes here.</div>

So what I want to happen is when you click “show box” and the box is revealed, the text then changes to “hide box” and back again if the box is hidden again. I’ve seen it done loads but can’t find it in a tutorial!

Hope someone can help

Many thanks

This jQuery plugin has all of your answers :slight_smile:

Within your click handler

$(this).text($(this).text() == 'Show box' ? 'Hide box' : 'Show box');
1 Like

Thanks for the suggestion alecrust but I want to amend my current code if possible. Joebert could you show me exactly how to implement your suggestion I’m not sure where I’m supposed to put your code : /

Thanks so far!

Put it here:


$('a#slickbox-toggle').click(function() {
    $('#slickbox').slideToggle(400);
    $(this).text($(this).text() == 'Show box' ? 'Hide box' : 'Show box'); // <- HERE
    return false;
});

Thats cracked it, Thanks so much!

For some reason I can’t use the text swapper twice??

I have duplicated the code (for some reason classes aren’t working on the box or the link) and now its stopped working (even the hiding of the boxes). If I remove the second text swapper then it all works but obviously the second lot of text isn’t being swapped.

Is there something wrong with my code?

<script type="text/javascript">
$(document).ready(function() {
 // hides the slickbox as soon as the DOM is ready
 // (a little sooner than page load)
  $('#agabox').hide();
 $('#mailbox').hide();

  // toggles the slickbox on clicking the noted link 
  $('a#agabox-toggle').click(function() {
    $('#agabox').slideToggle(400);
    $(this).text($(this).text() == 'Why do we need to know?' ? 'Read Below' : 'Why do we need to know?');
    return false;
});
  // toggles the slickbox on clicking the noted link 
  $('a#mailbox-toggle').click(function() {
    $('#mailbox').slideToggle(400);
   $(this).text($(this).text() == 'What's this?' ? 'Read Below' : 'What's this?');
    return false;
     
});
});
</script>

thanks for this guys, works a treat.