What is the best way to incorporate a function within a $.click (jquery) event that utilizes an id directly from the clicked element?

It seems that my title may not be very clear, but I have a jQuery code snippet that is causing some issues. The problem stems from the fact that when I click on an image with the class 'slideimg', I expect a function named slideDo to be executed, however, the browser console outputs an error:

Uncaught ReferenceError: slideDo is not defined
at HTMLAnchorElement.onclick (index.html:85)

The variable id used in the slideDo function is retrieved from the clicked image's id attribute using $(this).attr('id'). To make this work properly, I attempted to define the function within the click event handler itself. Unfortunately, this approach did not yield the desired outcome.

Within the HTML markup, the slideDo function is called upon clicking previous or next navigation buttons:

<div class="middle">
  <a class="prev" onclick="slideDo(-1)"> ❮ </a>
  <div class="imglink">
    <img src="img/dailyui/008.png" class="previewimg 1">
    <img src="img/dailyui/007.jpg" class="previewimg 2">
    <img src="img/dailyui/006.jpg" class="previewimg 3">
    <img src="img/dailyui/003.jpg" class="previewimg 4">
  </div>
  <a class="next" onclick="slideDo(1)"> ❯ </a>
</div>

In summary, my goal is to create a slideshow where clicking on an image triggers a modal display of related pictures. While the initial image clicking functionality works as intended, navigating through the images using the previous and next buttons appears to be malfunctioning. For a live demonstration, you can visit beta.eduardstefan.com

Answer №1

In this scenario, the function named slideDo is limited to the click event handler, but it seems like you are attempting to access it from the global scope (specifically from the onclick attribute of an anchor element). To make this work, you should set the function as a global variable.

var slideDo = function() {}; // starts with no functionality

$(document).ready(function() {
    $("img.slideimg").click(function(){
        var id = $(this).attr('id');
        $("img.previewimg." + id).css({"display": "block"});
        $("div.imgpreview").css({"display": "flex"});

        slideDo = function(n) {
            var i;
            var aux = id - 1 + n;
            var slidesp = document.getElementsByClassName("previewimg");
            if (aux > slidesp.length) {aux = 1}
            if (aux < 1) {aux = slidesp.length}
            for (i = 0; i < slides.length; i++) {
            slidesp[i].style.display = "none";
        }
        slidesp[aux-1].style.display = "block";
        }
    });
});

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

"JQuery's selector is failing to locate elements once they have been loaded through an

I am facing an issue where jQuery selectors are not working on elements loaded from the server via Ajax requests, but they work fine in normal mode. $('#myid').change(function(){ alert('OK!'); }); <select id="myid"> <optio ...

Tips to avoid the page from scrolling to the top when the menu is opened

Whenever a user taps the menu button on the page, a full-page menu opens. However, there is an issue - the main content page automatically scrolls to the top. Can you provide suggestions on how to prevent this from happening? I have already looked into a s ...

Struggling to achieve desired output from function in NextJS

I'm a bit confused by the code below. The itmLoop function seems to work fine when placed directly in the return section, but nothing is output when it's called as shown below? I'll eventually need to make it recursive, so I have to keep i ...

Setting a pre-selected value in a Vue.js dropdown list involves a few simple steps. This

Currently, I am developing two Vue components. I am sending array data from the parent component to the child component using props. Now, I have a requirement to pre-select a value in the dropdown list of the child component. Below is a snippet of my code ...

"Experience the power of MVC single page CRUD operations paired with dynamic grid functionality

Currently attempting to create a single page application CRUD functionality using UI Grid, however encountering an error during post request. ...

Having trouble deploying a Heroku app using Hyper? Here's a step-by-step guide to

After running the following commands: https://i.stack.imgur.com/WZN35.png I encountered the following errors: error: src refspec main does not match any error: failed to push some refs to 'https://git.heroku.com/young-brook-98064.git' Can anyon ...

I am looking for a highly specialized jQuery selector that fits my exact requirements

Hello everyone, I'm encountering an issue with a jQuery selector. Here is the HTML code snippet: <div id="Id_Province_chzn"> <a href="javascript:void(0)" class="chzn-single chzn-default" tabindex="-1"> <span> + this.default_tex ...

What is the method for showcasing a single Observable from an Array of Observables in Angular?

I am facing a challenge with displaying questions from an Observable-Array one by one. Currently, I can only display all the questions at once using *ngFor in my HTML. Here is my component code snippet: import { Component, OnInit } from '@angula ...

The error message "Failed to load the default credentials in Firebase" occurs sporadically. Approximately 50% of the time, the app functions properly, while the other 50% of the time, this specific

Occasionally in my firebase functions log, I encounter an error message stating: "Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information." This error appears randomly withi ...

Does jQuery mobile lack a back button feature?

Thoughts swirling in my mind: <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title></title> <script src="<?php echo base_url();?>/assets/js/vendor/modern ...

You need to pass a function as the first parameter when using passport-local-mongoose as a schema plugin

I've been struggling with implementing passport-local-mongoose in my server. I followed a tutorial video but encountered an issue that wasn't addressed in the video - even though my database is connected to mongodbatlas. The error message "First ...

Vuetify vueJS dialog with elevated design

Is there a way to completely remove the elevation of a v-dialog so that it has no shadow at all? The elevation property in the v-dialog itself and using the class as Class = "elevation-0" have not worked for me. Here is the link to the component ...

Running function without the need to click on 'li' element

In the process of developing a simple guessing game, my aim is to allow users to click on a number and have that number stored as userAnswer, while the computerAnswer is a randomly generated number between one and ten. Despite setting the setVariables() f ...

The issue of JavaScript failing to connect to the HTML file

As I work on my basic HTML file to learn Javascript, I believed that the script was correctly written and placed. Nevertheless, upon loading the file in a browser, none of the script seems to be functioning. All of my javascript code is external. The follo ...

How to Dynamically Update Sass Styles with Webpack 2?

Currently, I am in the process of setting up a React application that utilizes Webpack2, webpack-dev-middleware, and HMR for the development phase. One peculiar issue that I have encountered is related to updating .scss files. When I make changes to my .sc ...

The function is not explicitly declared within the instance, yet it is being cited during the rendering process in a .vue

import PageNav from '@/components/PageNav.vue'; import PageFooter from '@/components/PageFooter.vue'; export default { name: 'Groups', components: { PageNav, PageFooter, }, data() { return { groups: ...

How can client-side routing be effectively utilized?

I have a question about the utilization of AngularJS and Node.js in my web application. I have implemented client-side routing using routeProvider to navigate within different pages. All data is retrieved from a RESTful API server-side. However, most of ...

Is it possible to modify the labels on CKEditor's toolbar elements?

Initializing CKEditor in the following manner: function init() { $( ".ckeditor" ).ckeditor( { format_tags: 'h3;p', toolbar: [ [ "Source", "-", "Bold", "Italic" ], [ "Link", "Unlink" ], [ "Blockquote", "F ...

The ideal login page design

I apologize for my lack of knowledge in React, but I am quite new to it and have been struggling with this issue for days. I am having trouble creating a login page in ReactJS. Here is the code in my app.js: import React from 'react'; import {Ha ...

Guide on parsing JSON data received from the frontend

Here is the HTML code that I am working with: <div id="loginform"> <form class="loginIn" name="loginform"> <input type="text" name="login"> <input type="password" name="password"> <input type="submit" value="Войт ...