tags:

views:

2032

answers:

3

Does anybody know how to toggle text the html text of an anchor tag using Jquery. I want an anchor that when clicked the text alternates between "Show Background" & "Show Text" as well as fading in & out another div. This was my best guess:

$(function() {
    $("#show-background").click(function () {
    $("#content-area").animate({opacity: 'toggle'}, 'slow'); 
});

$("#show-background").toggle(function (){
    $(this).text("Show Background")
    .stop();
}, function(){
    $(this).text("Show Text")
    .stop();
});
});

Thanks in advance.

A: 
$(function() {
    $("#show-background").click(function () {
        $("#content-area").animate({opacity: 'toggle'}, 'slow'); 
    });

    var text = $('#show-background').text();
    $('#show-background').text(
        text == "Show Background" ? "Show Text" : "Show Background");
});

Toggle hides or shows elements. You could achieve the same effect using toggle by having 2 links and toggling them when either is clicked.

Kyle Butt
A: 

Modifying my answer from your other question, I would do this:

$(function() {
 $("#show-background").click(function () {
  var c = $("#content-area");
  var o = (c.css('opacity') == 0) ? 1 : 0;
  var t = (o==1) ? 'Show Background' : 'Show Text';
  c.animate({opacity: o}, 'slow');
  $(this).text(t);
 });
});
fudgey
Wow will take me a bit work how this is working but thanks for the help I will try it out!
mtwallet
BTW I have now linked to jQuery 1.4 and broken down the Tools library isolating only the parts I need. I think the conflict was with the Flash Embed part of the library.
mtwallet
In case you didn't know, the `o` and `t` are defined in a ternary operator (http://en.wikipedia.org/wiki/Ternary_operation).... and oops I forgot to add `var` in front - I will edit that now
fudgey
A: 

Sorry the problem is me! the was out of sync but this was because I have the HTML text the wrong way around. On the first click I want the div to fade out and the text to say "Show Text".

Will check more thoroughly next time before I ask!

My code is now:

$(function() {
        $("#show-background").toggle(function (){
            $("#content-area").animate({opacity: '0'}, 'slow')
            $("#show-background").text("Show Text")
            .stop();
        }, function(){
            $("#content-area").animate({opacity: '1'}, 'slow')
            $("#show-background").text("Show Background")
            .stop();
        });
    });

Thanks again for the help!

mtwallet