The function assigned to [variable].onclick is not being executed, despite no errors being displayed in the console

I'm new to javascript and I'm looking for help with a simple task. I want to create a code that when clicking on an image, it will open in a modal. This feature is important for viewing full-size images on my portfolio. Although there are no errors showing in the console, nothing happens when I click on the image.

Here is the javascript code:

var modal = document.getElementById("myModal");
var srcImg = document.getElementsByClassName("showFull");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
srcImg.onclick = function () {
    modal.style.display = "block";
    modalImg.src = this.src;
    modalImg.alt = this.alt;
    captionText.innerHTML = this.alt;
}

var exit = document.getElementsByClassName("close")[0];

exit.onclick = function () {
    modal.style.display = "none";
};

And here is the HTML code:

<div class="mySlides fade">
    <img class="slide showFull" src="images/mikesHarder.jpg alt="caption 123" style="width:100%" />
</div>

<div class="mySlides fade">
    <img class="slide showFull" src="images/Going-Green.jpg" alt="caption 123" style="width:100%" />
</div>

<div id="myModal" class="modal">
    <span class="close">&times;</span>
    <img id="img01" class="modal-content"/>
    <div id="caption"></div>
</div>

Lastly, we have the CSS code:

.showFull {
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

.showFull:hover { opacity: 0.9; }

.modal {
    display: none;
    position: fixed;
    z-index: 1;
    padding-top: 100px;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgb(0, 0, 0);
    background-color: rgba(0, 0, 0, 0.8);
}

.modal-content {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 480px;
}

.modal-content {
    animation-name: zoom;
    animation-duration: 0.6s;
}

@keyframes zoom {
    from {transform: scale(0)}
    to {transform: scale(1)}
}

.close {
    position: absolute;
    top: 15px;
    right: 35px;
    color: #f1f1f1;
    font-size: 40px;
    font-weight: bold;
    transition: 0.3s;
}

.close:hover,
.close:focus {
    color: #bbb;
    text-decoration: none;
    cursor: pointer;
}

@media only screen and (max-width: 700px) {
    .modal-content {
        width: 100%;
    }
}

Answer №1

One issue that arises is the fact that srcImg is an array of HTML elements rather than a single element. As a result, using srcImg.onclick will not work as expected since onclick can only be used with DOM objects that represent individual HTML elements.

Answer №2

    function handleImageClick(){
        var clickedElement = event.target;
        if(clickedElement.tagName !== "IMG"){ return }
        modal.style.display = "block";
        modalImg.src = clickedElement.src;
        modalImg.alt = clickedElement.alt;
        captionText.innerHTML = clickedElement.alt;
    }
<div onclick="handleImageClick()">
    <img src="./11.png" alt="111" >
</div>

srcImg is an array, it's recommended to use element.onclick = function(){...}

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

Executing multiple nested `getJSON` requests in a synchronous manner using jQuery

I am facing an issue with my code that connects to an API using $.getJSON. It retrieves JSON data and then iterates three times through a for loop because the data has 3 objects. During each of these iterations, it makes another $.getJSON call to fetch spe ...

Creating Multiple Choice Forms in React: A Guide to Implementing Conversational Form

I've been exploring React (Next.js) and I came across an interesting example of how to use multiple choice in simple HTML on Codepen ([https://codepen.io/space10/pen/JMXzGX][1]). Now I'm curious about how to implement a similar functionality in R ...

Identifying the relationship between child and parent components in Vue.js

I am new to Vue.js and I am practicing some simple exercises on communication between Vue components. However, I am struggling with understanding who is a child component and who is a parent component. For example, consider the following code snippet: HTM ...

What is the process for loading a .x model in Three.js?

Could anyone provide guidance on how to successfully load an animated .x model in Three.js? I am currently struggling with the process and have attempted to convert the .x model to collada without success. Unfortunately, my search for a free program to c ...

Apply rounded corners to the table row

Currently, I am utilizing a datagrid to display information. I have been attempting to implement border radius on all the table rows, but it doesn't seem to be working. Does anyone have insight into how I can apply border-radius to all rows in the t ...

Promise<IDropdownOption[]> converted to <IDropdownOption[]>

I wrote a function to retrieve field values from my SPFx list: async getFieldOptions(){ const optionDrop: IDropdownOption[]= []; const variable: IEleccion = await sp.web.lists.getByTitle("Groups").fields.getByTitle("Sector").get ...

Changing an object received as a prop in Vue.js

Is it acceptable to mutate values in a prop when passing an Object reference? In the process of developing a web application that involves passing numerous values to a component, I am exploring the most efficient method of handling value passing between c ...

Using multiple selectors in JQuery and Javascript

I have a challenge where I need to execute different actions for specific divs. Here is the code snippet I currently have: $("#pending-cancel-1, #pending-cancel-2").click(function(){ Do something special for pending-cancel-1 and pending-cancel-2... }) ...

Acquire the stripe color scheme of Bootstrap tables

I have a Razor component that populates a series of divs within a container. Is there a way to utilize the table-striped color scheme for my odd divs without replacing it entirely? Alternatively, if I create a new CSS class called "Div-Stripe-Row." Can ...

Slider that allows range selection after midday

Currently facing a dilemma using the noUiSlider plugin. I have set up a time range picker starting from 6 am to 6 am the following day. Everything works smoothly until it reaches 23:59, but I need it to display 1:00, 2:00 instead of 25:00, 26:00 for the ...

Guide to properly deserializing a JSON string into a class with a nested List of different class members

I have a scenario where I am sending a JSON stringified "View" object from the browser to an ASP.Net Page Method using Jquery's $.Ajax(). The issue I am facing is that while the Javascript deserialization is successful for all the strings and integers ...

What is the process of configuring a custom domain for localhost:3000 in a React application?

"scripts": { "start": "cross-env NODE_PATH=src react-scripts start", "build": "cross-env NODE_PATH=src react-scripts build", } Is there a way to replace localhost:3000 with a custom domain in Rea ...

Using brush strokes to create a unique design on the canvas page

Currently, I am working on implementing a brush-like effect on a web page. The task involves providing multiple patterns/textures in the background and allowing users to drag their mouse to create the pattern effect on the page. If you want to see the st ...

Am I on the right track with my code?

Is the code I've written sufficient to position text above an image? It resembles the orange "Ask Question" button on StackOverflow, but without being a clickable button or link. The text is surrounded by an orange color and it works fine, but I' ...

Validation of 'e' Symbol in Input Type Number Using jQuery Validator

Hey everyone, I'm currently utilizing jQuery validator for an input field with the type of number. However, when I enter 1e1, it shows an error message saying "invalid number." Is there a way to allow numbers like 1e1 (which equals 10) without trigger ...

Activate a pointer cursor when hovering over a TextField in Material-ui design

Hey there! I'm new to Material-ui/ReactJS and I have a question. I'm trying to change the cursor to a pointer when hovering over a Material-ui TextField, but it's proving to be quite challenging. The default behavior is 'cursor: text&ap ...

What is the best way to have a sound play when the page is loaded?

Is there a way to automatically play a sound when the page loads? <audio src="song.mp3"> Your browser does not support the audio element. </audio> I've attempted it with the following method: <script type="text/javasc ...

Setting up a web server with a cyclical challenge

I've encountered an issue while hosting my server.js file with the configured API on Cyclic. The deployment was successful, but every endpoint call is returning a status 500 error. Additionally, I have hosted the React front-end on github pages. I&apo ...

Something went awry when I tried to divide the HTML and CSS code

<div class="col-md-12" style=""> <div class="col-md-4 linkdetail" class="cursor"> <div class="col-md-12" style="margin-bottom:40px"> <img src="/img/product3.png" style="display:inline-block;width:100%;"> </div ...

In the event that the final calculated total is a negative number, reset it to zero. Inform the user of an error through the use of a prompt dialog box

I'm having trouble getting the grand total to display as 0 when I enter all amounts in positive values and then change the unit prices to negative values. However, it works fine when I only enter negative values throughout. Can someone please help me ...