skip to Main Content

So I’ve created a very basic practice page, where clicking each button will bring up a picture of the country. Below the picture is some text.

My question is, how do you go about making the text below the picture also change with each button? For example, changing from "This is a picture of Spain" to "My mum likes cooking" etc when you hit the different buttons.

I read somewhere you can have multiple onclick events with ; between them, but I’m very new to Javascript and haven’t been able to work out how to use multiple onclick events.

My HTML with script Javascript is below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Birds</title>
    <link rel="stylesheet" type="text/css" href="styling.css">

</head>

<body>
    <main>
   
        <h1>Places</h1>
        <h2>Subheading Goes Here</h2>
        <img id="bannerImage" src="https://www.planetware.com/wpimages/2020/03/portugal-in-pictures-beautiful-places-to-photograph-lisbon.jpg" /> <br> <br />
        <p id ="text">This is a picture of Northern Ireland</p>
        <nav>
            <button class="mainbuttons" onclick="changeImage('https://www.planetware.com/wpimages/2020/03/portugal-in-pictures-beautiful-places-to-photograph-lisbon.jpg')">Northern Ireland</button>
            <button class="mainbuttons" onclick="changeImage('https://theworldpursuit.com/wp-content/uploads/2021/01/things-to-do-in-northern-ireland.jpg')">Ireland</button>
            <button class="mainbuttons" onclick="changeImage('https://d32uwaumftsuh7.cloudfront.net/Pictures/768x432/7/2/0/22720_gameofthronesthedarkhedges_thekingsroad_master_529527_crop.jpg')">Scotland</button>
            <button class="mainbuttons" onclick="changeImage('https://media.cntraveller.com/photos/611bf776db797d0116fd53ab/master/w_1600,c_limit/causeway-coast-in-antrim-northern-ireland-gettyimages-1193546847.jpg')">Wales</button>
            <button class="mainbuttons" onclick="changeImage('https://onhisowntrip.com/wp-content/uploads/2020/08/Great-British-Chefs-1.jpg')">Spain</button>         
        </nav>

        <button id="themechanger" onclick="toggleTheme()">Toggle Theme</button>

<script>
function changeImage(fileName) {
let img = document.querySelector('#bannerImage');
img.setAttribute('src', fileName);
}

function toggleTheme(){
window.theme = typeof(window.theme)==='string' ? window.theme : 'root';
var switchToTheme = window.theme === 'root' ? 'dark' : 'root';
window.theme = switchToTheme;
document.querySelector('html').setAttribute('data-theme',switchToTheme);
}
</script>

</body>


    </main>
     
</body>
</div>
</html>

I’ve tried various internet tutorials, but nothing seems to fit

2

Answers


  1. There are a few ways to do this, but I think this is the easiest way with how you have it set up. I will explain the changes made and put the revised code at the bottom.

    1. Alter the ‘changeImage’ function to take in a new parameter which will be the element being clicked itself. To achieve this use the ‘this’ keyword as the first argument passed through.
    2. Change your function definition to accept 2 parameters and make the first one be what the ‘this’ keyword will replace.
    3. Create a variable that holds the

      element where the text will be placed.

    4. Using string interpolation/template strings, set the inner text of the

      element to match the same sentence you have by default, then get the clicked elements inner text (name of country) and add it to the sentence.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Birds</title>
        <link rel="stylesheet" type="text/css" href="styling.css">
    
    </head>
    
    <body>
        <main>
       
            <h1>Places</h1>
            <h2>Subheading Goes Here</h2>
            <img id="bannerImage" src="https://www.planetware.com/wpimages/2020/03/portugal-in-pictures-beautiful-places-to-photograph-lisbon.jpg" /> <br> <br />
            <p id ="text">This is a picture of Northern Ireland</p>
            <nav>
                <button class="mainbuttons" onclick="changeImage(this,'https://www.planetware.com/wpimages/2020/03/portugal-in-pictures-beautiful-places-to-photograph-lisbon.jpg')">Northern Ireland</button>
                <button class="mainbuttons" onclick="changeImage(this,'https://theworldpursuit.com/wp-content/uploads/2021/01/things-to-do-in-northern-ireland.jpg')">Ireland</button>
                <button class="mainbuttons" onclick="changeImage(this,'https://d32uwaumftsuh7.cloudfront.net/Pictures/768x432/7/2/0/22720_gameofthronesthedarkhedges_thekingsroad_master_529527_crop.jpg')">Scotland</button> <!-- 1. Add this keyword to functions -->
                <button class="mainbuttons" onclick="changeImage(this,'https://media.cntraveller.com/photos/611bf776db797d0116fd53ab/master/w_1600,c_limit/causeway-coast-in-antrim-northern-ireland-gettyimages-1193546847.jpg')">Wales</button>
                <button class="mainbuttons" onclick="changeImage(this,'https://onhisowntrip.com/wp-content/uploads/2020/08/Great-British-Chefs-1.jpg')">Spain</button>         
            </nav>
    
            <button id="themechanger" onclick="toggleTheme()">Toggle Theme</button>
    
    <script>
    function changeImage(element,fileName) { // 2. Add the 'element' parameter, which will be the button clicked
    let img = document.querySelector('#bannerImage');
    img.setAttribute('src', fileName);
    var textContainer = document.querySelector('#text'); // 3. Get the variable that holds the text and should be changed
    textContainer.innerHTML = `This is a picture of ${element.innerHTML}` //4. Generate your desired string and embed the buttons text which holds the country its linked to                
    }
    
    function toggleTheme(){
    window.theme = typeof(window.theme)==='string' ? window.theme : 'root';
    var switchToTheme = window.theme === 'root' ? 'dark' : 'root';
    window.theme = switchToTheme;
    document.querySelector('html').setAttribute('data-theme',switchToTheme);
    }
    </script>
    
    </body>
    
    
        </main>
         
    </body>
    </div>
    </html>
    Login or Signup to reply.
  2. The suggestion is to ..

    The advantages are …

    • a better markup which improves code-reuse, maintainability and even the user experience.
    • a total separation of markup and code …
    • … and a well defined place of where to provide the necessary data to.
    function handleBannerChangeFromBoundData({ target }) {
      // - always assure the intended button-target especially
      //   in case a button element does feature child elements.
      target = target.closest('button');
    
      if (target) {
        const { bannerSrc = "", bannerText = "" } = target.dataset;
        const { elmImage, elmCaption } = this;
    
        elmImage.src = bannerSrc;
        elmCaption.textContent = bannerText;
      }  
    }
    
    function initializeDynamicBanner(rootNode) {
      const elmImage = rootNode.querySelector('figure > img');
      const elmCaption = rootNode.querySelector('figure > figcaption');
      const elmNavigation = rootNode.querySelector('nav');
    
      elmNavigation.addEventListener(
        'click',
        handleBannerChangeFromBoundData.bind({
          elmImage,
          elmCaption,
        }),
      );
    }
    
    initializeDynamicBanner(
      document.querySelector('#dynamic-banner')
    );
    body { margin: 0; }
    h1, h2 { margin: 0; font-size: .9em; }
    h2, figcaption { font-size: .8em; }
    figure { margin: 3px 0 7px 0; }
    figure img { max-height: 150px; width: auto; }
    <main>
      <h1>Places</h1>
    
      <h2>Subheading Goes Here</h2>
    
      <article id="dynamic-banner">
        <figure>
          <img
            src="https://www.planetware.com/wpimages/2020/03/portugal-in-pictures-beautiful-places-to-photograph-lisbon.jpg"
            alt="Somewhere in Lisboa"
          >
          <figcaption>Somewhere in Lisboa</figcaption>
        </figure>
    
        <nav>
          <button
            data-banner-src="https://www.planetware.com/wpimages/2020/03/portugal-in-pictures-beautiful-places-to-photograph-lisbon.jpg"
            data-banner-text="Somewhere in Lisboa"
          >Lisboa</button>
          <button
            data-banner-src="https://theworldpursuit.com/wp-content/uploads/2021/01/things-to-do-in-northern-ireland.jpg"
            data-banner-text="Things to do in northern Ireland"
          >Northern Ireland</button>
          <button
            data-banner-src="https://d32uwaumftsuh7.cloudfront.net/Pictures/768x432/7/2/0/22720_gameofthronesthedarkhedges_thekingsroad_master_529527_crop.jpg"
            data-banner-text="The king's road"
          >Scotland</button>
          <button
            data-banner-src="https://media.cntraveller.com/photos/611bf776db797d0116fd53ab/master/w_1600,c_limit/causeway-coast-in-antrim-northern-ireland-gettyimages-1193546847.jpg"
            data-banner-text="Not Wales stupid, but causeway coast in Antrim Northern Ireland"
          >Wales</button>
          <button
            data-banner-src="https://onhisowntrip.com/wp-content/uploads/2020/08/Great-British-Chefs-1.jpg"
            data-banner-text="Not Spain, but great British chefs"
          >Spain</button>
        </nav>
    
      </article>
    </main>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search