"Implement a feature in JavaScript that allows users to click on images to navigate

I have a navigation feature on my website that allows me to cycle through images using the following code:

<a href="JavaScript:previousImage()">Previous</a> | <a href="JavaScript:nextImage()">Next</a> 
  <span id='num'></span>

The actual image codes are included below. While the Previous / Next links function properly, I would like to implement a feature where users can click directly on an image to navigate to the next one in sequence. For example, clicking on "1.jpg" should take the user to "2.jpg", and so on. Once "5.jpg" is clicked, it should loop back to "1.jpg". Any guidance on how to achieve this would be greatly appreciated. As a beginner building my site independently, any assistance is invaluable.

<script type="text/javascript">

var image = new Array("jpegs/1.jpg",
"jpegs/2.jpg",
"jpegs/3.jpg",
"jpegs/4.jpg",
"jpegs/5.jpg"
)

var imgNumber=1

var numberOfImg = image.length

function previousImage(){
  if(imgNumber > 1){
    imgNumber--
    }

  else{
    imgNumber = numberOfImg
    }

document.slideImage.src = image[imgNumber-1]

  }
function nextImage(){
  if(imgNumber < numberOfImg){
    imgNumber++
    }

  else{
    imgNumber = 1
    }

document.slideImage.src = image[imgNumber-1]

  }

</script>

Answer №1

Why not try this instead:

document.slideImage.addEventListener('click', nextImage);

Additionally, I recommend utilizing event listeners for the anchors as well:

document.slideImage.onclick = nextImage;

Answer №2

Avoid using href="Javascript:function()". Here's a sample approach to tackle this issue...

<script type="text/javascript">
  window.onload = function() {
    var count = 0;
    var images = ["jpegs/1.jpg", "jpegs/2.jpg", "jpegs/3.jpg", "jpegs/4.jpg", "jpegs/5.jpg"];
    var element = document.getElementById('slideImage');
    var previous = function() {
      count -= 1;
      if(count < 0) count = images.length - 1;
      element.setAttribute('src', images[count]);
    };        
    var increment = function() {
      count += 1;
      if(count >= images.length) count = 0;
      element.setAttribute('src', images[count]);
    };
    element.onclick = increment;
    document.getElementById('nextlink').onclick = increment;
    document.getElementById('prevlink').onclick = previous;
  };
</script>

This technique does not pollute the global namespace with variables (except for window) and only necessitates an id attribute.

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

Welcome to the awe-inspiring universe of Typescript, where the harmonious combination of

I have a question that may seem basic, but I need some guidance. So I have this element in my HTML template: <a href=# data-bind="click: $parent.test">«</a> And in my Typescript file, I have the following code: public test() { alert( ...

What is the process for including a scope in an Angular.js HTTP controller?

I am looking to access a $scope variable within this controller in order to utilize Angular functions like ng-click and ng-change in my HTML. Currently, I am only able to use the $http function but unable to execute any Angular methods on it. I am struggli ...

Separate an array in TypeScript based on the sign of each number, and then replace the empty spaces with null objects

Hey, I'm facing a little issue, I have an Array of objects and my goal is to split them based on the sign of numbers. The objects should then be dynamically stored in different Arrays while retaining their index and getting padded with zeros at the b ...

Is it more efficient to declare a variable or directly return the variable from the Element's getText() promise in Protractor?

I am facing a scenario where I need to retrieve the text of a web element using a promise and then extract a specific part of the string for further processing. Which example, the one at the top or the bottom, should I use? var id = element(by.binding( ...

Guide to updating information in Firestore using Node.js, embedded in a map array

Encountered an issue with the following error message: Error: Unable to access 'set' property of undefined. I am attempting to update the endTime field in my script for each user, calculate total hours worked, and then update the 'totalTi ...

Navigating through directories in an HTML file

In my directory, the folders are named in uppercase letters and have the following structure: ONLINESHOP |-- index.html |-- COMPONENTS |-- CONFIG |-- TEMPLATES |-- CSS |-- main-style.css |-- CONTROLLERS |-- MODE ...

Is it possible to deactivate dynamic binding in Vue.js?

I'm curious if there's a way to disable dynamic binding for a specific instance of an attribute that I'm displaying. Imagine I have the following code, utilizing two-way binding: this.$children[0].$data.hits In this scenario, I have a vac ...

Step-by-step guide on achieving 100% height for the <main> element in a Material UI drawer demo

I have a question regarding the Material UI drawer. In my project, I am trying to change the background color of the main tag. However, the main tag's height is restricted to the content inside. Check out this link for reference Setting the height t ...

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 ...

Combining Entities Using Immutable JavaScript

Currently utilizing React, Redux, and Immutable. I have a question about merging a plain JavaScript object into an Immutable Map object. Importing Immutable.js: import { List as iList, Map as iMap } from "immutable"; The content of action.paylo ...

What's preventing me from tapping on hyperlinks on my mobile device?

I'm currently working on a website (saulesinterjerai.lt) and everything seems to be functioning properly, except for the fact that on mobile devices, the links aren't clickable and instead navigates to other layers. How can I disable this behavio ...

An exploration of effortlessly moving elements using webdriver.io - the power of

I have been attempting to utilize the drag and drop method in WebDriver.io, but I am encountering issues. I followed the example for drag & drop on this website: https://www.w3schools.com/html/html5_draganddrop.asp. This functionality is essential for ...

Incorporating descriptions below the images within this JavaScript carousel

I'm struggling to add text under the images in this slider. The functionality is simple, but I can't figure it out. I might have to rewrite it. Here's the HTML and JS: <div id="look-book-scroll"> <a href="javascript:;" id="lookbo ...

Using Nuxtjs/Toast with personalized image emblems

Would it be possible to include an icon in a toast error message, or is there a need to install another module for this functionality? I am currently using vue and attempting to integrate a component as an icon, but so far without success. this.$toast.er ...

Leveraging JavaScript code repeatedly

Apologies if this question has been asked before, as I couldn't find it. I have an HTML table with images used as buttons: <td> <button class="trigger"> <img src="D:\Elly Research\ CO2858\Presentation\Calypso ...

Utilize the entire width for header elements

I have implemented four header elements: home, about, portfolio, and contact. I want these elements to stretch across the entire navigation bar with each taking up 25% of the space. How can I achieve this? Additionally, I specified that the home element sh ...

Implementing a hybrid design using the display flex property

Any suggestions on the most effective way to achieve the following layout using flexbox? I want 2 rows with columns of equal width, but the last column should be 100% height and fill the remaining space in the section. Should I consider using multiple row ...

Encountering infinite loop in Node modules triggering a Catch-22 situation while attempting to use M

I have been working on a project that involves using some customized Node.js modules. I have developed a 'helpers' module that helps with loading various helper methods: /helpers/index.js: var mutability = require('./mutability'), ...

How to retrieve the current event handler's value with jQuery

To assign an onclick event handler using jQuery, I simply use the following code: $('#id').click(function(){ console.log('click!'); }); Now, my question is how can I retrieve a reference to the function that is currently handling th ...

Dealing with scenarios where the DOM undergoes changes that overwrite certain variables

I am currently using Ruby on Rails, jQuery version 1.8.3, and jQuery UI version 1.9.2 within my project. Within a view file, I have implemented the rendering of a partial template in the following manner: <%= render :partial => 'template_name&a ...