Skip to content

Instantly share code, notes, and snippets.

@shaneriley
Created February 26, 2013 15:12
Show Gist options
  • Save shaneriley/5039142 to your computer and use it in GitHub Desktop.
Save shaneriley/5039142 to your computer and use it in GitHub Desktop.
jQuery toggleText() http://jsbin.com/ajinox/4
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="toggleText.js"></script>
<meta charset=utf-8 />
<title>Character Limit</title>
</head>
<body>
<a href="#" data-alt_text="Unfriend">Add to friends</a>
<p>Not friends</p>
</body>
</html>
$(function() {
$("a").click(function(e) {
e.preventDefault();
$(this).toggleText();
$("p").toggleText("Friends", "Not friends");
});
});
/* jQuery toggleText plugin
Used to toggle between two text values. Either pass in two strings or set a data-alt_text attribute
on the element you're calling toggleText from to toggle its text node between two values.
Examples at http://jsbin.com/ajinox/4
*/
(function($) {
$.fn.toggleText = function(a, b) {
var new_text = a || b;
if (!a && !b) {
new_text = this.attr("data-alt_text");
}
if (!new_text) { return this; }
if (this.attr("data-alt_text")) {
this.attr("data-alt_text", this.text());
}
else {
console.log(this.text());
new_text = this.text() === a ? b : a;
}
this.text(new_text);
return this;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment