Swapping between set text?


this is what the project looks like so far, im wondering if there is a way to have sets of text for each of the navbar buttons i have so far and if i can swap between them on the same webpage in the same location below the buttons?

Thanks in advance.

Hi @HazzaBean

Do you mean if you click a button the navbar buttons text would change in place?

[Who is Sun Tzu?] [The Art Of War Sun] [Tzu Legacy] [Mythology]
             # Press a button then they become #
[New Text] [More New Text] [Different Text To Before] [Totally New Text]
                                    

More so

Default on [Who is Sun Tzu?]

Normal text underneath my navbar with a description of Sun Tzu

Click [The Art Of War]

Previous text describing who Sun Tzu is now replaced with text about art of war

Click [Sun Tzu Legacy]

Previous text replaced with text about the legacy

so on so on

Ohhh, I see. There’s a couple of ways you could do it with JavaScript, the easiest is probably to store the text in an array, then depending on what button is clicked, it would then apply that correct text into a generic container underneath the navbar.

So underneath your navbar you could have a generic text container like:

<nav>...</nav>
<div class="text-container"></div>

Then in JavaScript you want something like:

// Store these in the same order the buttons appear.
var textArray = ['who is sun text', 'art of war text', 'legacy text', 'mythology text'];

$('button').click(function() {
  // Finds the clicked buttons index, which will match up with the text array.
  var textIndex = $(this).index();

  // Inserts the correct text from the textArray using the buttons index.
  $('.text-container').text(textArray[textIndex]);
});

That should do what you want.

1 Like

Worked great thanks!

http://codepen.io/HazzaBean/full/GrNJBO/ this is what i finished the first challenge on. took me a little bit of time since i wanted to fully understand how the array was working but i think i understand it now.

if you have a few seconds could you tell me if there is anything that stands out to you as wrong or just simply could have been done better? i’m trying to stop bad habits early so its easier.

Thanks again.

No worries dude.

I would say that your better off utilising codepens different language tabs, rather than putting all the html, css and JavaScript inside the html.

You can also customise the page with scripts and link tags inside the project settings. So to the left of HTML/CSS/JS there is a gear icon, if you click that and click HTML at the top, there is a ‘Stuff for head’ box, in there you can put link tag for the google font. In JavaScript under ‘Add External JavaScript’ you can put the URL for jQuery.

I’ve actually tidied up and organised the code for you (below), a couple of notes on what I did. Obviously you don’t need to use what I’ve changed, it’s just easier to explain this way rather than making notes all over the code :grin:.

  • Removed unecassary code from HTML (codepen automatically adds doctype, body, head tags etc…). As an aside, if you were to keep it in the HTML, you want to move the footer tag above the script tag inside the body as it’s currently sitting outside the body; this doesn’t affect the way it displays but is a best practice.
  • I moved the jQuery code that colours the buttons into css under .btn { … }, no need to have them separately in JavaScript.
  • I moved all the JavaScript inside the .ready function, you had it there it just wasn’t being used.
  • Fixed indentation, you want to try and keep everything indented properly, it makes code much easier to read.

I hope this helps!

// HTML
<h1 class="text-center">Sun Tzu</h1> 
<h2 class="text-center">Master Tactcian</h2>
<img class="center-block img-responsive img-rounded thin-grey-border" alt="Statue of Sun Tzu in Yurihama, Tottori, in Japan" src="https://media.licdn.com/mpr/mpr/shrinknp_800_800/AAEAAQAAAAAAAAlZAAAAJDQ2MjJlMDk0LWYyZDMtNGYxNC1hNWU1LTk5NWIxZjMyOGQwZg.jpg"></img>
<div class="caption text-center" id="Image-Caption">
  Statue of the mythical Sun Tzu in Yurihama, Tottori, in Japan
</div>
<div class="navbar clearfix">
  <nav class="text-center"id="navbar">
    <button class="btn" type="button" onclick="WhoIsSunTzu()" >Who is Sun Tzu? </button> 
    <button class="btn" type="button" onclick="TheArtOfWar()"> The Art Of War </button>
    <button class="btn" type="button" onclick="SunTzuLegacy()"> Sun Tzu Legacy</button>
    <button class="btn" type="button" onclick="Mythology()"> Mythology </button>
  </nav> 
  <div class="text-container-fluid text-center" id="MainPage"></div>
</div>
<footer class="text-center" id="footer"> 
  <p> <a href="https://en.wikipedia.org/wiki/Sun_Tzu" target="_blank"> Sun Tzu </a> Wiki </p>
  <p> Written By <a href="https://www.freecodecamp.com/hazzabean" target="_blank"> Harry Waterman</a>. </p>
</footer>
// CSS
h1 {
  font-family: lobster, monospace;
  font-size: 72px;
}
body {
  background-color: #c2c4c2;
}
h2 {
  font-family: lobster, monospace;
  font-size: 48;
}
.thin-grey-border{
  border-color: #4e4e4f;
  border-width: 5px;
  border-style: solid;
}
#Image-Caption {
  font-family: lobster, monospace;
  margin-top: 10px;
}
#navbar {
  font-family: monospace;
  background-color: #4e4e4f;
  margin-top: 20px;
  margin-bottom: 20px;
  
}
#footer{
  font-family: monospace;
  font-color: #4e4e4f;
}
#MainPage{
  font-family: monospace;
  font-color: #4e4e4f;
  font-weight: bold;
  margin-left: 40px;
  margin-right: 40px;
}
button {
  background: #06337c:
  color: white;
}
// JavaScript
$(document).ready(function() {
  var textArray = ['Who Is Sun Tzu? Sun Tzu was a Chinese general, military strategist, and philosopher who lived in the Spring and Autumn period of ancient China. Sun Tzu is traditionally credited as the author of The Art of War, a widely influential work of military strategy that has affected both Western and Eastern philosophy. Aside from his legacy as the author of The Art of War, Sun Tzu is revered in Chinese and the Culture of Asia as a legendary historical figure. His birth name was Sun Wu, and he was known outside of his family by his courtesy name Changqing. The name Sun Tzu by which he is best known in the West is an honorific which means "Master Sun."', 'The Art of War is an ancient Chinese military treatise dating from the 5th century BC. Attributed to the ancient Chinese military strategist Sun Tzu. The text is composed of 13 chapters, each of which is devoted to one aspect of warfare. It is commonly thought of as a definitive work on military strategy and tactics. It was placed at the head of Chinas Seven Military Classics upon the collections creation in 1080 by Emperor Shenzong of Song, and has long been the most influential strategy text in East Asia. It has had an influence on Eastern and Western military thinking, business tactics, legal strategy and beyond.The book was first translated into French in 1772 by the Jesuit Jean Joseph Marie Amiot and a partial translation into English was attempted by British officer Everard Ferguson Calthrop in 1905. The first annotated English translation was completed and published by Lionel Giles in 1910. Leaders such as Mao Zedong, General Vo Nguyen Giap, General Douglas MacArthur and leaders of Imperial Japan have drawn inspiration from the work.', 'Sun Tzus Art of War has influenced many notable figures. Sima Qian recounted that Chinas first historical emperor, Qins Shi Huangdi, considered the book invaluable in ending the time of the Warring States. In the 20th century, the Chinese Communist leader Mao Zedong partially credited his 1949 victory over Chiang Kai-shek and the Kuomintang to The Art of War. The work strongly influenced Maos writings about guerrilla warfare, which further influenced communist insurgencies around the world.The Art of War was introduced into Japan c. AD 760 and the book quickly became popular among Japanese generals. Through its later influence on Oda Nobunaga, Toyotomi Hideyoshi, and Tokugawa Ieyasu, it significantly affected the unification of Japan in the early modern era. Prior to the Meiji Restoration, mastery of its teachings was honored among the samurai and its teachings were both exhorted and exemplified by influential daimyōs and shoguns. Subsequently, it remained popular among the Imperial Japanese armed forces. The Admiral of the Fleet Tōgō Heihachirō, who led Japans forces to victory in the Russo-Japanese War, was an avid reader of Sun Tzu.Ho Chi Minh translated the work for his Vietnamese officers to study. His general Vo Nguyen Giap, the strategist behind victories over French and American forces in Vietnam, was likewise an avid student and practitioner of Sun Tzus ideas.', 'Beginning around the 12th century, some scholars began to doubt the historical existence of Sunzi, primarily on the grounds that he is not mentioned in the historical classic The Commentary of Zuo (Zuo zhuan 左傳), which mentions most of the notable figures from the Spring and Autumn period. The name "Sun Wu" (孫武) does not appear in any text prior to the Records of the Grand Historian, and has been suspected to be a made-up descriptive cognomen meaning "the fugitive warrior": the surname "Sun" is glossed as the related term "fugitive" (xùn 遜), while "Wu" is the ancient Chinese virtue of "martial, valiant" (wǔ 武), which corresponds to Sunzis role as the heros doppelgänger in the story of Wu Zixu. Unlike Sun Wu, Sun Bin appears to have been an actual person who was a genuine authority on military matters, and may have been the inspiration for the creation of the historical figure "Sunzi" through a form of euhemerism.'];

  $('button').click(function() {
    var textIndex = $(this).index();

    $('.text-container-fluid').text(textArray[textIndex]);
  });
});

That’s a real big help yeah.

i feel like the two major things there are i wanted to include those things for when i’m not relying on codepen and switching over to my editor atom which i was using before i started with codecamp.

so with atom iv’e got things to specifically clean up my code nicely and make sure its indented correctly etc haha, kinda lazy i know.

also would you say it would be worth me commenting some things as i go? just as a good practice or would that be more a waste of time than anything else?

I thought you might be doing it this way, I just wanted to show you how CodePen expects it because likely chance is you’ll be splitting code into HTML/CSS/JS files outside of CodePen in the future anyway, especially when you start on the more complicated projects.

Lol, nothing wrong with that, I would say as you’re learning try and force yourself to do it manually, it’s easier to debug things when you have more of an understanding of what’s going on, even for something as simple as indentation.

Definitely, if you get into a good habit of commenting code (especially code that isn’t immediately clear what it’s doing) you’ll thank yourself in the long run.