Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript I'm not able to isolate my alert message to a specific image using an index reference to the array. Any thoughts?

Craig

New Coder
HTML:
<!DOCTYPE html>



<html lang="en">

<head>

    <title>Task 2</title>

</head>

<body>

    <img src="black.circle.png" onclick="myFunction()" />

    <img src="red.triangle.png" onclick="myFunction()" />

    <img src="blue.square.png" onclick="myFunction()" />

 



    <script>

        var myShapes = [

            "black.circle.png",

            "red.triangle.png",

            "blue.square.png",

        ];



    function myFunction() {

      if (myShapes[0])

    alert("This is a black circle image");

      }



    </script>



</body>

</html>
 
Last edited by a moderator:
Hey Craig! Looks like you’re close to the solution. 😊 To make each alert specific to the image clicked, you can pass an index to your myFunction to pull the correct message from the array. Here’s how:

Updated HTML​

Update each &lt;img&gt; tag to pass a unique index:

Code:
<img src="black.circle.png"    onclick="myFunction(0)" />

<img src="red.triangle.png"    onclick="myFunction(1)" />

<img src="blue.square.png"    onclick="myFunction(2)" />

Updated JavaScript​

In JavaScript, use that index to select the right message:

Code:
<script>    var myShapes = [        "This is a black circle image",        "This is a red triangle image",        "This is a blue square image"    ];    function myFunction(index) {          alert(myShapes[index]);      }  </script>

Explanation​

Each onclick now passes a unique index (0, 1, or 2) to myFunction, allowing it to pull the correct message from the myShapes array. This way, each alert will match the image clicked.

Hope that helps—let us know if it works! 😊
 

New Threads

Buy us a coffee!

Back
Top Bottom