The onclick function only triggers after the second click

I have an issue with my image view onclick function code. Currently, the code works perfectly but only when I click for the second time. I am not sure what the problem is and would appreciate any help in fixing it. Below is the code snippet:

<script type="text/javascript">

        function showimage(z)
        {
                var modal = document.getElementById('myModal'+z);
                var img = document.getElementById('myImg'+z);
                var modalImg = document.getElementById('img01'+z);
                var captionText = document.getElementById('caption'+z);

                img.onclick = function ()
                {
                    modal.style.display = "block";
                    modalImg.src = this.src;
                    captionText.innerHTML = this.alt;
                }
        }
    </script>

<span>
      <img src="<?php echo $u_pimg; ?>" alt="" class="newsize" id="myImg<?php echo $p_id; ?>" onclick="showimage(<?php echo $p_id; ?>)">
    enter code here
</span>

Answer №1

Initially, you are assigning the "showimage" function to trigger when the image is clicked, followed by another assignment

function ()
                {
                    modal.style.display = "block";
                    modalImg.src = this.src;
                    captionText.innerHTML = this.alt;
                }

upon clicking the image. There is no need to continuously assign the event to the image tag.

You can either remove onclick="showimage()" from your HTML tag or eliminate img.onclick from the JavaScript code.

Simply restructure it as follows:

function showimage(z)
        {
                var modal = document.getElementById('myModal'+z);
                var img = document.getElementById('myImg'+z);
                var modalImg = document.getElementById('img01'+z);
                var captionText = document.getElementById('caption'+z);

                 modal.style.display = "block";
                    modalImg.src = img.src;
                    captionText.innerHTML = this.alt;
        }

This adjustment will ensure smooth functionality.

Answer №2

Your code snippet is a bit unclear as it only provides a small portion of the entire code. One thing to note is that there seems to be an unnecessary onlick function inside the showimage function. To improve clarity, consider removing the inner img.onclick part.

     <script type="text/javascript">

        function showimage(z)
        {
                var modal = document.getElementById('myModal'+z);
                var img = document.getElementById('myImg'+z);
                var modalImg = document.getElementById('img01'+z);
                var captionText = document.getElementById('caption'+z);

                modal.style.display = "block";
                modalImg.src = img.src; // <- replace this with img
                captionText.innerHTML = img.alt;
        }
    </script>

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 for a Simplemodal popup to appear only once per user session

I'm completely new to javascript and jQuery. Recently, I've started using SimpleModal basic from SimpleModal to show a popup upon visitors landing on my website. Everything seems to be working perfectly, but there's one issue - the popup kee ...

What is the best way to execute an ajax call in a Ruby on Rails application?

Hey there, I am just starting to learn Ruby on Rails and I need help with making an ajax request. Here is the JavaScript code I have: $(document).ready(function(){ $(".form_submit").click(function() { var apiid = $('#apiid').val(); ...

Determined margin value to replicate the maximum and minimum margin in CSS styling

When attempting to set the margin on an object to 20% with a maximum margin of 200px, I experimented with various methods: margin-left: calc(min(200px, 20%)); and max-margin-left: 200px However, neither property proved to be valid. Is there an alterna ...

Customizing a unique dropdown navigation experience

I have very limited experience with using jQuery and CSS. I recently came across the DropIt jQuery plugin files (accessible at ) and decided to integrate it into my Ruby on Rails project. Unfortunately, I am struggling with implementing the "Hover Me" exa ...

Adding a Table Row in jQuery without Appending it to the Bottom of the Table

I am working on a project that involves an HTML Table where the user can add a new Row by clicking a button. However, I want the new Row to be added not at the end of the table, but after the last row of input fields. To demonstrate, I have prepared a sam ...

Implementing additional states in an AngularJS app configuration with Ui-Router

Currently tackling a major application with numerous routes for its different components, my team and I have decided to break down the routes into separate files instead of cramming everything into one large file. In attempting to create a variable and im ...

Using PHP/MySQL to enable users to make changes to their account details

I've successfully set up 2 pages update.php edit.php We begin on edit.php, so here is the script for edit.php <?php session_start(); $id = $_SESSION["id"]; $username = $_POST["username"]; $fname = $_POST["fname"]; $password = $_POST["password"]; ...

Disappearance of array data

I have been working on creating an array of objects with nested arrays, but I am facing an issue where data seems to go missing in the final step: const args_arr = []; const options_arr = []; let options = ''; let text = ""; for (let i = 0; ...

Ways to showcase a website within an HTML document using a URL?

Is it possible to show 2 webpages on a single aspx webpage? For instance, When a user opens the link for www.mywebsite.com, I would like to display both www.google.com and www.bing.com on my homepage. Behind the scenes, I will call two separate URLs an ...

What is the correct way to place an item within a grid layout?

My current layout is structured with a single row class and two columns using the bootstrap grid system. However, I am facing an issue where I need to add another item within that grid system, but I am struggling to position it correctly. It keeps appeari ...

Performing an ajax request in asp.net mvc 4 to a download controller

One of the functionalities I have involves performing a download operation like so: [HttpGet] public void Download(string FileName) { string FilePath = System.AppDomain.CurrentDomain.BaseDirectory + "Exe\\"; System.Web. ...

Issues with Bootstrap split button display malfunctioning

Experiencing an issue with a Bootstrap split button while working on a test Drupal website. Although it seems to be working fine in Codepen and JSFiddle, on this particular website, the dropdown component appears to be getting pushed under the button. Desp ...

There was an error that said: "Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type

I keep encountering the error Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type whenever I utilize the .apply() method but I'm unable to pinpoint the cause. You can review my code here. Upon loading jsfiddle, try clicking ne ...

Leveraging server.ts for Development with Angular 5 Universal

I decided to give the new Angular Universal Starter a try for my latest Angular 5 project. Instead of providing multiple options, they now only offer the Angular CLI version as a starting point. I've been able to successfully run my project in product ...

Having trouble with Autocomplete Search feature in Laravel?

I have a search field with the same name and id on both my categories page and products page. The autocomplete suggestions are working fine, but when I click on a suggested product in the search field, it stays on the same page instead of redirecting me to ...

<div> issues with background display

I have created two different sections with distinct backgrounds. However, I am facing an issue where these two divs are not appearing on the webpage. My intention is to position the Navbar at the top and have another section below it that is not linked to ...

Issue with ERR_HTTP_HEADERS_SENT persists despite implementation of return statements

When attempting to send a POST request to the server, an error is encountered: Error [ERR_HTTP_HEADERS_SENT]: Cannot modify headers after they are sent to the client at new NodeError (node:internal/errors:371:5) at ServerResponse.setHeader (node:_h ...

Enhance ngx-bootstrap's tab content with ngx-scrollbar functionality

Currently in my project, I am utilizing bootstrap 4 and ngx-bootstrap. One requirement I have is to develop a component consisting of 2 scrollable divs that can be switched by tabs. I was hoping to demonstrate a sample application on stackblitz, but unfor ...

A step-by-step guide on splitting an element into two separate elements using jquery

I have the following code snippet: <h4>user (role) on 26 Nov 2018 20:39:42 +00:00:</h4> My goal is to transform it into this structure: <h4>user (role)</h4> <p>on 26 Nov 2018 20:39:42 +00:00:</p> The <h4> eleme ...

React does not always remove event listeners when using the useEffect hook's return callback

I have a functionality in my component where it initializes a key event listener. This event is supposed to trigger an API call to fetch random data. useEffect(() => { const keyUpEvent = (event) => { if (event.code === "Enter") { ...