Having trouble with JavaScript in a project I'm trying to replicate

For my coding practice, I am working on a project where clicking on the images should change the main product displayed along with its color. However, nothing happens when I click on the products. Can anyone point out what I might be doing wrong?

Here is the code snippet that I have:

        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Menu</a></li>
            <li><a href="#">What's New</a></li>
            <li><a href="#">Contact</a></li>

        </ul>
    </header>
    <div class="content">
        <div class="textbox">
            <h2>It's not just Coffee<br>It's <span>Starbucks</span></h2>
            <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor 
                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
                quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
                Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu 
                fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, 
                sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
                <a href="#">Learn More</a>
        </div>
        <div class="imgBox">
            <img src="img/img1.png" class="starbucks"
        </div>
    </div>
    <ul class="thumb">
        <li><img src="img/thumb1.png" onclick="imgSlider('img1.png');changeCircleColor('#017143')"></li>
        <li><img src="img/thumb2.png" onclick="imgSlider('img2.png');changeCircleColor('#eb7495')"></li>
        <li><img src="img/thumb3.png" onclick="imgSlider('img3.png');changeCircleColor('#d752b1')"></li>
    </ul>
    <ul class="sci">
        <li><a href="#"><img src="img/facebook.png"></a></li>
        <li><a href="#"><img src="img/twitter.png"></a></li>
        <li><a href="#"><img src="img/instagram.png"></a></li>
    </ul>
</section>

<script type="text/javascript">
    function imgSlider(anything){
        document.querySelector('.starbucks').src = anything;
    }

    function changeCircleColor(color){
        const circle = document.querySelector ('circle');
        circle.style.background = color;
    }
</script>

Answer №1

If you want to improve the clarity, readability, and maintainability of your code, I suggest diving into the world of data-attributes.

Check out more information here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

Before we jump into modifying your code, let's address some bugs present in it:

  1. Make sure to include . before the className when using querySelector
// Incorrect
document.querySelector ('circle');

// Correct way
document.querySelector('.circle')
  1. The Document method querySelector() either returns the first element that matches the specified selector or group of selectors. If no match is found, null is returned – which would result in returning a group of selectors in your code.

Let's now proceed to make your code functional:

  1. Create a function to handle the onclick event.

Learn more about JavaScript events here: https://www.w3schools.com/js/js_events.asp

function handleImageClick(event) {
// @TODO insert your logic here.
}
  1. Add two data-attributes (data-image="" and data-color="") to each image and attach the event handler created earlier.
<ul class="thumb">
  <li><img src="img/thumb1.png" onclick="handleImageClick(this)" data-image="img1.png" data-color="#017143"></li>
  <li><img src="img/thumb2.png" onclick="handleImageClick(this)" data-image="img2.png" data-color="#eb7495"></li>
  <li><img src="img/thumb3.png" onclick="handleImageClick(this)" data-image="img3.png" data-color="#d752b1"></li>
</ul>
  1. Time to create the logic:
function handleImageClick(event) {
  var target = event;
  
  // Get the color and image from data-attributes
  var color = target.dataset.color;
  var image = target.dataset.image;
  
  // Output details to console
  console.log(color, image)
  
  target.style.backgroundColor = color;
  target.src  = image;
}

View a live example here: https://codepen.io/nawafscript/pen/eYEKBJJ

I hope this explanation clarifies things for you.

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

Rows in a table will not decrease when added anew

On a page that allows adding and deleting rows from a table of input fields, the following code functions properly for existing fields. However, when attempting to add new rows and delete them in a sequential manner that requires replacing the ID and name ...

Is there a way to extract data from the Redux state in a React component?

Seeking assistance with making an API request from Redux, followed by saving the data in my React state (arrdata). Although the API call is successful, I am facing challenges updating the App.js state based on the Redux API call. Any suggestions or insig ...

Unexpected appearance of blank space to the right of my parallax design

Ever since a forced reboot, my parallax scrolling page has been experiencing issues. A strange whitespace seems to be throwing off the sections, only appearing every other section - one is fine, the next is offset, and so on. I've carefully gone thro ...

Step-by-step guide on incorporating an external JavaScript library into an Ionic 3 TypeScript project

As part of a project, I am tasked with creating a custom thermostat app. While I initially wanted to use Ionic for this task, I encountered some difficulty in integrating the provided API into my project. The API.js file contains all the necessary function ...

Encountering a problem with React components displaying incorrect sizes while utilizing flexbox styling

I am creating a basic test application using NextJS/React. Take a look at the code snippet below: The content of Board.tsx file: import './Board.css'; export default function Board() { return <div className="board"> < ...

Executing a serverless function in Next.js using getStaticPaths: A step-by-step guide

In my current project, I am utilizing Next.js and the Vercel deployment workflow. To set up page generation at build time, I have been following a guide that demonstrates how to generate pages based on an external API's response. // At build time, t ...

Setting a custom background image in HTML using the designated file PATH

My current issue involves the inability to set my background photo using a CSS file. I am utilizing NetBeans for this project. Inside a folder named css, there is a file called global.css which contains the following code: body{ background-image: url ...

Unleashing the y-axis and enabling infinite rotation in Three.js

In my three.js project, I am utilizing orbital controls. By default, the controls only allow rotation of 180 degrees along the y-axis. However, I would like to unlock this restriction so that I can rotate my camera infinitely along the y-axis. As someone ...

Tips on enhancing SauceLabs javascript queries in your selenium testing for faster speeds?

My experience running Selenium tests on the Chrome browser in SauceLabs has been quite frustrating due to the sluggish performance. One of the major issues I have encountered is the significant delay in javascript queries, taking about 200ms to return res ...

Having trouble retrieving the API URL id from a different API data source

For a small React project I was working on, I encountered a scenario where I needed to utilize an ID from one API call in subsequent API calls. Although I had access to the data from the initial call, I struggled with incorporating it into the second call. ...

The functionality of Bootstrap 5's modal-dialog-scrollable seems to be malfunctioning

I recently created a Student Add form using bootstrap 5 <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dial ...

Display a button only when hovering over it

Seeking assistance for a simple task that is eluding me at the moment. I am currently using scss and trying to make a button only appear when hovered over. The button is hidden in the code snippet below, nested within a block alongside some svgs. Any hel ...

Can you provide a guide on setting up and utilizing mathlive within NuxtJS?

Can anyone assist me? I am trying to figure out why my code is not working or if I have implemented it incorrectly. I used npm i mathlive to obtain input. However, following the instructions for implementing nuxt plugins in the documentation has not yield ...

How can Angular JS detect the names of the CSS files being used in an HTML page?

I am in the process of developing a brand new widget where we are incorporating a unique feature that displays the number of CSS files included within an HTML page. Our team requires the count and names of all CSS files utilized on the webpage. While I a ...

"Error: The function $(...).autocomplete is not recognized" in conjunction with Oracle Apex

Currently experiencing some frustration trying to solve the issue at hand. The Uncaught TypeError: $(...).autocomplete is not a function error keeps popping up and I have exhausted all resources on Stack Overflow in an attempt to fix it. This problem is oc ...

Guide to deactivating a control within a User Control

I anticipated that making this change would be straightforward, but I am encountering some difficulties. Initially, my asp.net markup for the server control appears like this: <ucTextArea:UserControlTextArea ID="taRemarks" runat="server" /> However ...

Angular's UI Modal: utilizing inline template and controller functionality

I am looking to create a simple confirmation box using UI-modal, which I have used successfully for more complex modals in the past that load their template and controller from external files. However, this time I want something even simpler - just a basi ...

Steps for transforming a matplotlib animation into an HTML5 `<video>` element

Here is the code for a matplotlib animation graph and you can find instructions on how to save it here. from IPython.display import HTML import matplotlib.pyplot as plt import matplotlib.animation import numpy as np t = np.linspace(0,2*np.pi) x = np.sin ...

Customizing AxiosRequestConfig with Axios in TypeScript can greatly enhance the functionality and

Currently working with React and Axios. Lately, I've been experimenting with custom configurations in Axios as shown below: import $axios from 'helpers/axiosInstance' $axios.get('/customers', { handlerEnabled: false }) However, wh ...

A Step-by-Step Guide to Successfully Clicking on a Checkbox Using Selenium and Python

Hello everyone, I'm facing an issue with clicking a checkbox. Here is the code for the checkbox: <label class="has-checkbox terms"><input name="order[terms]" type="hidden" value="0" /><input class="checkbox" type="checkbox" value=" ...