How to toggle Text and toggle HTML with jQuery - toggleText(), toggleHTML()

Hot to toggle text or even other HTML content inside an HTML element using JavaScript and jQuery
How to toggle Text and toggle HTML with jQuery - toggleText(), toggleHTML()
How to toggle Text and toggle HTML with jQuery - toggleText(), toggleHTML()

This is a very simple function (included in all KAS websites). The plugins look like this:

$.fn.toggleText = function(t1, t2){
 if(this.text() == t1){
  this.text(t2);
}else{                   
  this.text(t1);
}
 return this;
};

 

$.fn.toggleHTML = function(t1, t2){
if(this.html() == t1){
  this.html(t2);
}else{                   
  this.html(t1);
}
return this;
};

 

To use them simply add two parameters with the before and after text to toggle, make sure that t1 (the original text or HTML) is already present inside your HTML Element.

For example a classic hamburger menu using font awesome:

//HTML
<span class="togMobile"><i class="fas fa-bars" aria-hidden="true"></i></span>
 
//JS
$('.togMobile').click(function(){
      $('.mainMenu').slideToggle();
      $(this).toggleHTML('<i class="fas fa-bars" aria-hidden="true"></i>','<i class="far fa-times" aria-hidden="true"></i>');
});

 

Or a simple Open / Close text

//HTML
<span class="status">Open</span>
//JS
$('.status').click(function(){
      $(this).toggleText('Open','Close');
});

 

 

Comments

Get a Quote

Get a Quote