What is the process for displaying an image when an event listener for a click event is triggered?

Can you explain how SetAttribute is utilized in JavaScript? I recently started learning JS and wanted to expand on a lesson from a website called 30 Days of JS to deepen my understanding of the language.

My goal is to display an image whenever any of the "circle" elements are clicked on.

Since I am just starting out with JS, I would appreciate it if you could break down the concept in simple terms, avoiding complex or fancy solutions that may not help me grasp the fundamentals effectively.

Thank you in advance!

Below is the code snippet I have been working on:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <title>Randomy</title>
    <link rel="stylesheet" href="styles.css">
</head>

<body>

    <div class="circles">
        <div data-key="81" class="circle">
            <kbd>Q</kbd>
            <span class="img">clap</span>
        </div>
        <div data-key="87" class="circle">
            <kbd>W</kbd>
            <span class="img">hihat></span>
        </div>
        <div data-key="69" class="circle">
            <kbd>E</kbd>
            <span class="img">kick</span>
        </div>
        <div data-key="82" class="circle">
            <kbd>R</kbd>
            <span class="img">openhat</span>
        </div>
        <div data-key="84" class="circle">
            <kbd>T</kbd>
            <span class="img">boom</span>
        </div>

        <img hidden data-key="81" src="img/icecream.jpg" />
        <img hidden data-key="87" src="img/mini-popsicles.jpg" />
        <img hidden data-key="69" src="img/mini-poptarts.jpg" />
        <img hidden data-key="82" src="img/mini-potpie.jpg" />
        <img hidden data-key="84" src="img/rainbow_ring.jpg" />

    <script>
        document.addEventListener("click", myFunction); 

        function myFunction() {
            var oy = document.getElementsByClassName("circles")[0];
            oy.getElementsByClassName("circle")[0].setAttribute("src", "img/mini-popsicles.jpg"); 
        }

    </script>

    </body>

Answer №1

Implementing the setAttribute function works as intended, however, the issue lies in the attribute being set.

It seems that the elements with the class circle are actually divs which do not have a src attribute.

To resolve this, consider using images that are initially hidden (display:none;) and then through JavaScript, dynamically set the src attribute upon a user action such as a click event, making sure to adjust the display property accordingly.

Alternatively, you can utilize background-images within the div to achieve the desired image display effect.

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

Is it possible to bypass the confirmation page when submitting Google Form data?

Is there a way to bypass the confirmation page that appears after submitting a form? What I would like is for the form to simply refresh with empty data fields and display a message saying "your data has been submitted" along with the submitted data appea ...

Switch Between More and Less Text - Implement Smooth Transition on Shopify Using Javascript

I recently implemented a More/Less toggle button using resources from this website. The functionality is there, but I now want to add a smooth transition effect. When the user clicks on "read more," I would like the hidden content to gradually appear, and ...

Switching the URL without reloading the page in NEXT.JS

Currently, I am in the process of building an ecommerce store using NEXT.JS and Redux. Within the product listing page, I have incorporated a sorting select dropdown featuring options such as Price Low to High, Price High to Low, and New Arrivals. My goal ...

Save the function as a local variable and preserve the reference to the current object

In the prototype of my Car object, I have a function that looks like this: Car.prototype.drive = function() { this.currentSpeed = this.speed; } I find myself needing to call this drive function frequently within another function of the Car prototype. ...

Incorporate information produced by a Javascript function into PHP

I have developed a website which pulls data from a file (a time value) and initiates a Javascript timer. My goal is to use PHP to continue adding the current time to the loaded time, resulting in an incremental timer that resumes from where it was last l ...

The CSS link will only appear when hovering over the image

I'm having trouble getting the f1 link to appear on an image only when hovering over the image. I tried some code but it's not working, the link is not appearing. Can someone help me understand what the problem is and provide a solution? <div ...

nextjs-auth0: refresh user session after updating user_metadata without requiring user to log out and log back in

I'm currently facing a challenge with fetching a user's updated data from Auth0 after modifying the user_metadata: Here is a simplified index file. In this scenario, the user chooses an object and can mark it as a favorite. When the user selects ...

Utilize jQuery to set a cookie, then apply the bodyclass retrieved from the cookie upon page

I have a button that changes the body class to .blackout For this, I am utilizing js-cookie library to manage cookies. The code snippet associated with my button is shown below: <script> $('#boToggle').on('click', function(e) { ...

Updating the KML data on Google Maps V3 for a fresh look

I recently updated a map from V2 to V3 and I am working on incorporating code to automatically refresh the KML data every 30 seconds. The goal is to update the map with the latest data and display a countdown until the next refresh. Here is an example of ...

Searching for a cake in CakePHP with autocomplete functionality

$( "#skills" ).autocomplete({source: function(request, response) { $.getJSON("http://server/current/indrealestates.com/properties/autosuggesthome/",{ term:request.term ,extraParams:$('#property_id').val()}, response ); }, ...

Ways to address the problem of returning assignments

I encountered an issue while working on my code Error message: Arrow function should not return assignment no-return-assign The problematic code snippet is as follows: await DB.Place.find( match, // key to filter (err, doc) => (listOfObje ...

Trigger file upload window to open upon clicking a div using jQuery

I utilize (CSS 2.1 and jQuery) to customize file inputs. Everything is working well up until now. Check out this example: File Input Demo If you are using Firefox, everything is functioning properly. However, with Chrome, there seems to be an issue se ...

In a responsive design, rearrange a 3-column layout so that the 3rd column is shifted onto or above the

My question is concise and to the point. Despite searching online, I have not been able to find any information on this topic. Currently, my layout consists of 3 columns: ---------------------------- |left|the-main-column|right| ------------------------- ...

Limit access to all pages, with the exception of the home page, in Django

During the development of my Django application, I organized the functionality into sub-functions and implemented them in individual apps. To display results on the homepage instead of redirecting to a sub-function app page, I utilized ajax and JavaScript. ...

Is it recommended to utilize CDN in Vue.js for optimal performance?

Currently facing a version compatibility issue between leaflet and leaflet-draw in my vuejs project. In light of this, I am seeking alternative solutions for map function editing such as adding polylines, copy and paste functions, and more. While I did com ...

What are the steps to implementing imgix-js via command line?

$(document).ready(function () { var imgixOptions = { updateOnResizeDown : true, updateOnPinchZoom : true, fitImgTagToContainerWidth: true, fitImgTagToContainerHeight: true, autoInsertCSSBestPractices: true, ...

I'm encountering an issue where the data in my personalDeatail model's add value is not updating automatically. Can someone please help me

I've been struggling to automatically update the data in model personalDetail.add value when adding two column data. The added data appears correctly in the input box, but it's not updating in personalDetail.add. What am I missing here? Help need ...

Can you please explain the time and space complexity of this algorithm for obtaining all subarrays of a given array that are divisible by a specified number?

I've been working on a function that takes an array and an integer as parameters, returning an array of subarrays. The number of subarrays exactly matches the integer passed to the function, with each subarray containing continuous elements in the ori ...

Guide on retrieving documents from a collection in mongodb by utilizing the $nin operator

My user schema looks like this const userSchema= new mongoose.Schema({ Username:{ type:String, trim:true, required:true }, email:{ type:String, trim:true, required:true }, hashed_password:{ type:String, trim:t ...

How to add interactive dot hover to the end of a line chart in Highcharts

I am working on a line chart that currently lacks interactivity, and I want the final data point to reflect the hover circle dot color of the line. Please refer to the image for clarification - can you help me achieve this? Thanks, Daniel! Desired Outc ...