开发者

jQuery Toggle Text?

开发者 https://www.devze.com 2022-12-18 04:36 出处:网络
How to toggle 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 w

How to toggle 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")
     开发者_JAVA技巧   .stop();
    }, function(){
        $(this).text("Show Text")
        .stop();
    });
});


$(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.


The most beautiful answer is... Extend jQuery with this function...

$.fn.extend({
    toggleText: function(a, b){
        return this.text(this.text() == b ? a : b);
    }
});

HTML:

<button class="example"> Initial </button>

Use:

$(".example").toggleText('Initial', 'Secondary');

I've used the logic ( x == b ? a : b ) in the case that the initial HTML text is slightly different (an extra space, period, etc...) so you'll never get a duplicate showing of the intended initial value

(Also why I purposely left spaces in the HTML example ;-)

Another possibility for HTML toggle use brought to my attention by Meules [below] is:

$.fn.extend({
        toggleHtml: function(a, b){
            return this.html(this.html() == b ? a : b);
        }
    });

HTML:

<div>John Doe was an unknown.<button id='readmore_john_doe'> Read More... </button></div>

Use:

$("readmore_john_doe").click($.toggleHtml(
    'Read More...', 
    'Until they found his real name was <strong>Doe John</strong>.')
);

(or something like this)


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!


Improving and Simplifying @Nate's answer:

jQuery.fn.extend({
    toggleText: function (a, b){
        var that = this;
            if (that.text() != a && that.text() != b){
                that.text(a);
            }
            else
            if (that.text() == a){
                that.text(b);
            }
            else
            if (that.text() == b){
                that.text(a);
            }
        return this;
    }
});

Use as:

$("#YourElementId").toggleText('After', 'Before');


jQuery.fn.extend({
        toggleText: function (a, b){
            var isClicked = false;
            var that = this;
            this.click(function (){
                if (isClicked) { that.text(a); isClicked = false; }
                else { that.text(b); isClicked = true; }
            });
            return this;
        }
    });

$('#someElement').toggleText("hello", "goodbye");

Extension for JQuery that only does toggling of text.

JSFiddle: http://jsfiddle.net/NKuhV/


var el  = $('#someSelector');    
el.text(el.text() == 'view more' ? 'view less' : 'view more');


Why don't you just stack them ::

$("#clickedItem").click(function(){
  $("#animatedItem").animate( // );
}).toggle( // <--- you just stack the toggle function here ...
function(){
  $(this).text( // );
},
function(){
  $(this).text( // );
});


Use html() to toggle HTML content. Similar to fflyer05's code:

$.fn.extend({
    toggleText:function(a,b){
        if(this.html()==a){this.html(b)}
        else{this.html(a)}
    }
});

Usage:

<a href="#" onclick='$(this).toggleText("<strong>I got toggled!</strong>","<u>Toggle me again!</u>")'><i>Toggle me!</i></a>

Fiddle: http://jsfiddle.net/DmppM/


I've written my own little extension for toggleText. It may come in handy.

Fiddle: https://jsfiddle.net/b5u14L5o/

jQuery Extension:

jQuery.fn.extend({
    toggleText: function(stateOne, stateTwo) {
        return this.each(function() {
            stateTwo = stateTwo || '';
            $(this).text() !== stateTwo && stateOne ? $(this).text(stateTwo)
                                                    : $(this).text(stateOne);
        });  
    }
});

Usage:

...
<button>Unknown</button>
...
//------- BEGIN e.g. 1 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Show', 'Hide'); // Hide, Show, Hide ... and so on.
});
//------- END e.g. 1 -------

//------- BEGIN e.g. 2 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Unknown', 'Hide'); // Hide, Unknown, Hide ...
});
//------- END e.g. 2 -------

//------- BEGIN e.g. 3 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText(); // Unknown, Unknown, Unknown ...
});
//------- END e.g.3 -------

//------- BEGIN e.g.4 -------
//Initial button text is: 'Unknown'
$('button').on('click', function() {
    $(this).toggleText('Show'); // '', Show, '' ...
});
//------- END e.g.4 -------


Use this

jQuery.fn.toggleText = function() {
    var altText = this.data("alt-text");
    if (altText) {
        this.data("alt-text", this.html());
        this.html(altText);
    }
};

Here is how you sue it

 
   jQuery.fn.toggleText = function() {
    	var altText = this.data("alt-text");

    	if (altText) {
    		this.data("alt-text", this.html());
    		this.html(altText);
    	}
    };

    $('[data-toggle="offcanvas"]').click(function ()  {

    	$(this).toggleText();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button data-toggle="offcanvas" data-alt-text="Close">Open</button>

You can even use html provided it's html encoded properly


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


In most cases you would have more complex behavior tied to your click event. For example a link that toggles visibility of some element, in which case you would want to swap link text from "Show Details" to "Hide Details" in addition to other behavior. In that case this would be a preferred solution:

$.fn.extend({
  toggleText: function (a, b){
    if (this.text() == a){ this.text(b); }
    else { this.text(a) }
  }
);

You could use it this way:

$(document).on('click', '.toggle-details', function(e){
  e.preventDefault();
  //other things happening
  $(this).toggleText("Show Details", "Hide Details");
});


$.fn.toggleText = function(a){
    var ab = a.split(/\s+/);
    return this.each(function(){
        this._txIdx = this._txIdx!=undefined ? ++this._txIdx : 0;
        this._txIdx = this._txIdx<ab.length ? this._txIdx : 0; 
        $(this).text(ab[this._txIdx]);
    }); 
}; 
$('div').toggleText("Hello Word");


<h2 id="changeText" class="mainText"> Main Text </h2>

(function() {
    var mainText = $('.mainText').text(),
        altText = 'Alt Text';

    $('#changeText').on('click', function(){
        $(this).toggleClass('altText');
        $('.mainText').text(mainText);
        $('.altText').text(altText);
    });

})();


Perhaps I'm oversimplifying the problem, but this is what I use.

$.fn.extend({
    toggleText: function(a, b) {
        $.trim(this.html()) == a ? this.html(b) : this.html(a);
    }
});


Nate-Wilkins's improved function:

jQuery.fn.extend({
    toggleText: function (a, b) {
        var toggle = false, that = this;
        this.on('click', function () {
            that.text((toggle = !toggle) ? b : a);
        });
        return this;
    }
});

html:

<button class="button-toggle-text">Hello World</button>

using:

$('.button-toggle-text').toggleText("Hello World", "Bye!");


You can also toggleText by using toggleClass() as a thought ..

.myclass::after {
 content: 'more';
}
.myclass.opened::after {
 content: 'less';
}

And then use

$(myobject).toggleClass('opened');


this is not the very clean and smart way but its very easy to understand and use somtimes - its like odd and even - boolean like:

  var moreOrLess = 2;

  $('.Btn').on('click',function(){

     if(moreOrLess % 2 == 0){
        $(this).text('text1');
        moreOrLess ++ ;
     }else{
        $(this).text('more'); 
        moreOrLess ++ ;
     }

});


Why not keep track of the state of through a class without CSS rules on the clickable anchor itself

$(function() {
    $("#show-background").click(function () {
        $("#content-area").animate({opacity: 'toggle'}, 'slow');
        $("#show-background").toggleClass("clicked");
        if ( $("#show-background").hasClass("clicked") ) {
            $(this).text("Show Text");
        }
        else {
            $(this).text("Show Background");
        }
    });
});


var jPlayPause = $("#play-pause");
jPlayPause.text(jPlayPause.hasClass("playing") ? "play" : "pause");
jPlayPause.toggleClass("playing");

This is a piece of thought using jQuery's toggleClass() method.

Suppose you have an element with id="play-pause" and you want to toggle the text between "play" and "pause".

0

精彩评论

暂无评论...
验证码 换一张
取 消