jQuery toggleClass example

Toggle class name on click in jQuery

by Mike Gleeson

HTML

<div id="banner-message">
  <p>NWN Auto-Center Description</p>
  <textarea id='text'></textarea>
  <p id='error'>

  </p>
  <button id='generate'>Generate</button>
  
</div>

<br/>
<div id='resultDiv'>
  <p>Generated Text</p>
  <textarea id='result'></textarea>
  <button id='copy'>Copy to Clipboard</button>
</div>
<textarea type="text" id="output" style="opacity:0;"></textarea>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

#error
{
  color: red;
}

.hidden 
{
    display: none !important;
}

#resultDiv
{
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

JavaScript

// find elements
var banner = $("#banner-message");
var button = $("#generate");
var copy = $("#copy");
var resultDiv = $("#resultDiv");
var input = $("#text");
var result = $("#result");
var error = $("#error");
var copier = $("#output");

//copy text
copy.on("click", () => {
  /* Get the text field */
  var copyText = document.getElementById("output");

  /* Select the text field */
  copyText.select();
  copyText.setSelectionRange(0, 99999); /*For mobile devices*/

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
});



// handle click and add class
button.on("click", () => {
	
  banner.toggleClass("alt");
  resultDiv.removeClass("hidden");
  var textLength = input.val().length;
  var lines = $('textarea').val().split('\n');
  var output = "";
  for(var i = 0; i < lines.length; i++){
      //code here using lines[i] which will give you each line
      var line = lines[i];
      var lineLength = line.length-1;      
      var centered = 30 - lineLength;
      
      if(centered < 0) {
      	error.text("Invalid line detected, lines longer than 30 characters cannot be centered");
      }
      else {
         let lineModify = "";
      	 for(var j = 0 ; j < centered/2; j++) lineModify += " ";
         output += lineModify + line + lineModify + "\r";
      }
  }
  
  result.text(output);
  copier.text(output.replace(/(\r\n|\n|\r)/gm,"||"));
});