What could be causing my JavaScript function to not properly set the CSS display property to "inline" for an image element?

Objective: My goal is to design a webpage featuring a basic image of fruits. Upon clicking the image, it should transform into an array of 6 images showcasing various types of fruits such as apples, oranges, and bananas arranged in two rows with three images each. Here's the code snippet I have managed so far:

<!DOCTYPE html>
<html>
<head>
<style>
.Fruits img {border: 6px solid blue;
  width: 100px;
  height: 100px;
  cursor: pointer;
  display: none;
}
img {border: 6px solid blue;
  width: 100px;
  height: 100px;
  cursor: pointer;
}
</style>
</head>
<body>
<script>
function expand() {
  var fruit_all = document.getElementsByClassName("Fruits"); 
  var fruit = document.getElementsByTagName("fruit_all[0].img")
  for (j = 0; j < fruit.length; j++) {
    fruit[j].style.display = 'inline';
  } 
  var replaced = document.getElementsByTagName("img");
  replaced[0].style.display = 'none';
}
</script>

<h1>Fruit</h1>
<!--Generic Fruits image-->
<img src="https://wpcdn.us-east-1.vip.tn-cloud.net/www.hawaiimagazine.com/content/uploads/2020/12/exoticfruits-opener.jpg" 
height="100" width="100" onclick="expand()">

<!--This is what replaces the Generic Fruits image-->
<div class="Fruits">
<img src="https://foodprint.org/wp-content/uploads/2018/10/IMG_3392-e1539129880189.jpg" 
height="100" width="100">
<img src="https://foodprint.org/wp-content/uploads/2018/10/imageedit_127_5581342771.jpg" 
height="100" width="100">
<img src="https://i0.wp.com/moodymoons.com/wp-content/uploads/2016/02/img_8986.jpg?fit=4560%2C3000&ssl=1" 
height="100" width="100">
<img src="https://www.naturalhealth365.com/wp-content/uploads/2016/04/blueberries.jpg" 
height="100" width="100">
<img src="https://th.bing.com/th/id/OIP.gBifOTB-F-wBTx3bzYPiGgHaE-?pid=ImgDet&rs=1" 
height="100" width="100">
<img src="https://th.bing.com/th/id/OIP.3yrzbKoKIgyR7eBhHma26AHaGm?pid=ImgDet&rs=1" 
height="100" width="100">
</div>
</body>
</html>

I suspect there might be an issue with my expand() function. The aim is to target all elements under the .Fruits img class and change the display attribute to inline upon click. Although the initial generic fruits image disappears upon clicking, the subsequent 6 fruit images organized in a grid layout do not appear.

Answer №1

maybe it can look like this:

function showFruits() {
  var fruitsDiv = document.getElementsByClassName('Fruits')[0];
  fruitsDiv.style.display = 'block';
  var firstImg = document.getElementsByTagName('img')[0];
  firstImg.style.display = 'none';
}
function chooseImage(el){
 var newImage = el.src;
 var mainImage = document.getElementsByTagName('img')[0];
 mainImage.src =  newImage;
 mainImage.style.display = 'inline-block';
 var fruitsDiv = document.getElementsByClassName('Fruits')[0];
 fruitsDiv.style.display = 'none';
}
img {
  border: 6px solid blue;
  width: 100px;
  height: 100px;
  cursor: pointer;
}
.Fruits{
  display: none;
}
<h1>Fruit</h1>
<!--Generic Fruits image-->
<img src="https://wpcdn.us-east-1.vip.tn-cloud.net/www.hawaiimagazine.com/content/uploads/2020/12/exoticfruits-opener.jpg" onclick="showFruits();">

<!--This is what replaces the Generic Fruits image-->
<div class="Fruits">
  <img src="https://foodprint.org/wp-content/uploads/2018/10/IMG_3392-e1539129880189.jpg" onclick="chooseImage(this);">
  <img src="https://foodprint.org/wp-content/uploads/2018/10/imageedit_127_5581342771.jpg" onclick="chooseImage(this);">
  <img src="https://i0.wp.com/moodymoons.com/wp-content/uploads/2016/02/img_8986.jpg?fit=4560%2C3000&ssl=1" onclick="chooseImage(this);">
  <br>
  <img src="https://www.naturalhealth365.com/wp-content/uploads/2016/04/blueberries.jpg" onclick="chooseImage(this);">
  <img src="https://th.bing.com/th/id/OIP.gBifOTB-F-wBTx3bzYPiGgHaE-?pid=ImgDet&rs=1" onclick="chooseImage(this);">
  <img src="https://th.bing.com/th/id/OIP.3yrzbKoKIgyR7eBhHma26AHaGm?pid=ImgDet&rs=1" onclick="chooseImage(this);">
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Store the fetched data as JSON in the local storage

Struggling to find a solution after reading several articles, I am working on fetching a large JSON from an API and I want to cache the response in the localStorage. The goal is for the script to check for an object with the requested ID in the cached JSON ...

Designing a webpage layout using Bootstrap 4 that includes a horizontal/inline form and two columns

Just when I felt confident in my understanding of bootstrap, it seems to be giving me trouble :( I am aiming to create a layout with 2 columns, each containing a question followed by a small text box for entering a number. Here is an example of the layou ...

Firebase Error: Page Not Found

I recently set up an Angular2 application and added Firebase using npm. I successfully imported it into my app.component.ts without any errors showing up in my text editor. The package.json file also indicates that Firebase is installed correctly. However ...

What is the best way to adjust the specific scope of every element generated by ng-repeat within a directive?

Attempting to simplify tables in Angular, I am working on a directive. My goal is for the user to only need to provide the list object and the formatting of each list element in the HTML, using the my-table tag as shown below... <h3>My Table</h3& ...

Troubleshooting React Native's ScrollView issue with row direction and flexWrap not allowing scrolling

One issue I'm facing in my React Native app is with a ScrollView that contains a list of items wrapped in rows (flexDirection:'row', flexWrap:'wrap'). For some reason, the ScrollView is not scrolling properly... Here is the code f ...

Is there a way to properly access and interpret a .log extension file within a React component?

import React from "react"; import "./App.css"; function FileReaderComponent() { const readLogFile = () => { if (window.File && window.FileReader && window.FileList && window.Blob) { const preview = document.getElementByI ...

show content with ajax and php

I am attempting a simple task with ajax, but it's not working as expected. All I want is to display some text when the input button is clicked. ajax.js jQuery(document).ready(function($) { $('#insertForm').change(function(){ // Retrieve th ...

The Vue app utilizing Flickr API encounters an issue: "Unable to assign value to 'data' property as it is undefined."

Beginning the development of a simple one-page photo stream app using the public Flickr stream, I've encountered an error in my code: 'Cannot set property 'data' of undefined'. Here is a snippet of my code: <b-container> ...

The unexpected identifier 'express' was encountered in the import call, which requires either one or two arguments

I'm in the process of constructing an express server using typescript and Bun. Recently, I completed my register route: import express from "express"; const router = express.Router(); router.get('/registerUser',(_req:express.Reque ...

The innerHTML function in jQuery seems to be malfunctioning

My div isn't displaying the expected content. This is my controller action: /// <summary> /// GetCountiresForManufacturer /// </summary> /// <returns></returns> [Authorize(Roles = "Administrator")] [Ac ...

Top tip for handling repetitive code with echo commands

I've been struggling with a question for quite some time now. Imagine you have a code that consists of multiple nested divs and spans, forming a square with an image inside. echo '<div> <div> <div> <div> <span> < ...

Methods for bypassing a constructor in programming

I am working on a code where I need to define a class called programmer that inherits from the employee class. The employee class constructor should have 4 parameters, and the programmer class constructor needs to have 5 parameters - 4 from the employee c ...

Upcoming API and backend developments

When working with the NEXT project, API Routes provide the ability to create an API endpoint within a Next.js application. This can be achieved by creating a function in the pages/api directory following this format: // req = HTTP incoming message, res = H ...

Is there a way to get this reducer function to work within a TypeScript class?

For the first advent of code challenge this year, I decided to experiment with reducers. The following code worked perfectly: export default class CalorieCounter { public static calculateMaxInventoryValue(elfInventories: number[][]): number { const s ...

Exploring the process of fetching and showcasing API responses through AJAX

I need to pass the value of my car to an API, which is retrieved from the HTML below. After that, I would like to send this value to the API using AJAX. Finally, I want to display all the models in the same way as I displayed the cars. $(document).r ...

Utilizing Timer Control for Image Rotation in Presentations

I have two sets of images named Div1 and Div2 that need to be displayed in a slideshow. The condition is as follows: For the first seven days, I want the images from the first set, Div1, to appear in the slideshow. Once the seven days are over, the images ...

What methods can be used to test scss subclasses within an Angular environment?

Exploring different background colors in various environments is a task I want to undertake. The environments include bmw, audi, and vw, with each environment having its own unique background color. Need help writing an Angular test for this? How can I mod ...

Is it possible to utilize scrollTop without the need to create a separate function?

I am currently facing an issue with my jQuery code and was searching for some answers on how to enhance my existing slideDown function. One particular question from 2010 caught my attention, you can find it here: http://stackoverflow.com/questions/4034659 ...

Endless loop in XMLHttpRequest()

I am trying to use Ajax in the code snippet below to continuously retrieve a PHP query result until it reaches "6". The code seems to be functioning correctly, but once the result is "6", the script does not stop running. Instead, my CPU fan starts making ...

Changing color when mouse hovers using Jquery

Currently, I am in the process of converting a flash ad into an html5 ad. I found this demo here, and I would like to replicate the mouse hover effect showcased. When the cursor hovers over the details text in the banner, the entire background changes to ...