Switching pictures upon clicking next or previous

Hi there! I'm wondering if it's possible to change the hidden_div image by clicking on either prev. or next using this JS code?

<a href="#"><div onClick="show(this);" class="img" style="background-image:url('css/images1/img/img1.jpg');")></div></a>
   <a href="#"><div onClick="show(this);" class="img" style="background-image:url('css/images1/img/img2.jpg');")></div></a>
   <a href="#"><div onClick="show(this);" class="img" style="background-image:url('css/images1/img/img3.jpg');")></div></a>

<div id="hidden_div"></div>
<a href="#" onClik="next(-1)">prev</a>
<a href="#" onClik="next(1)">next</a>


<script>
function show(element) {
    var hidden = document.getElementById("hidden_div"); 
    var imgURL = element.style.backgroundImage.replace('url(','').replace(')','');    
    var imgElement = "<img src="+ imgURL +" />" 
    hidden.innerHTML  = imgElement;
};

var step=1;
var total=3;
 function next(x){ 
    var image=document.getElementById("hidden_div");

    step=step+x;
    if(step > total){step=1;}
     if(step <1 ){step=total;}
     image.src= 'css/images1/img/img " + step + ".jpg';
   };   

Answer №1

The issue with the src change not working is because in your next() function, you are attempting to set the src attribute to a div element instead of the image inside it.

The image that needs to be changed does not have an id, so to target the image within your div tag, you should use getElementById() to target the div and then apply getElementsByTagName to target the <img>.

getElementById().getElementsByTagName()[0]

function next(x){ 
    step=step+x;
    if(step > total){step=1;}
     if(step < 1 ){step=total;}
     document.getElementById("hidden_div").getElementsByTagName('img')[0].src='css/images1/img/img'+step+'.jpg'
}

If you have any queries regarding the solution, feel free to drop a comment below and I'll respond promptly. (Understanding the source code is crucial for grasping the answer!)

Edit: Working Demo...

Additionally, please note that the anchor tag used to trigger the next function is incorrect.

<a href="#" onClick="next(-1)">prev</a>

The correct attribute should be onClick instead of onClik. It may seem like a minor typo, but it has a significant impact on the code.

function show(element) {
    var hidden = document.getElementById("hidden_div"); 
    var imgURL = element.style.backgroundImage.replace('url(','').replace(')','');    
    var imgElement = "<img src="+ imgURL +" />" 
    hidden.innerHTML  = imgElement;
}
var total=3;
var step=1;
 function next(x){ 
    step=step+x;
    if(step > total){step=1;}
     if(step < 1 ){step=total;}
     document.getElementById("hidden_div").getElementsByTagName('img')[0].src='https://dummyimage.com/150x150/000/fff&text='+step+'.jpg'
   }
.img{height:150px;width:150px;border:solid red 1px;display:inline-block;}
<div onClick="show(this);" class="img" style="background-image:url('https://dummyimage.com/150x150/000/fff&text=1.jpg');")>1</div>
<div onClick="show(this);" class="img" style="background-image:url('https://dummyimage.com/150x150/000/fff&text=2.jpg');")>2</div>
<div onClick="show(this);" class="img" style="background-image:url('https://dummyimage.com/150x150/000/fff&text=3.jpg');")>3</div><br/>
<button onClick="next(-1);">Prev</button><button onClick="next(1);">Next</button>
<div id="hidden_div"></div>

I trust this information proves valuable. Keep coding happily!

Answer №2

It seems that the problem lies in the undefined variables step1 and total1. Have you considered replacing those variables with step and total for clarity?

function next(x)
{ 
    var image=document.getElementById("hidden_div");
    var step=step+x;
    if(step > total) 
       step=1;
    else if(step <1 )
       step=total;
    image.src= 'css/images1/img/img'+step+'.jpg';
}  

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

The element fails to receive the class when it is being clicked

Currently, I am in the process of developing a Joomla website and I am working on implementing an accordion feature for the category descriptions based on the placement of H3 headings in the WYSIWYG editor. Here is the basic function I have so far (althou ...

Eliminate the presence of core-js in the nextjs bundle

Currently, I am tackling the challenge of minimizing bundle sizes in my Next.js project. One particular aspect that caught my attention is the inclusion of a core-js bundle for polyfills. This adds an extra 50KB to the size of the main bundle, which I aim ...

What are the best practices for incorporating Javascript into a page with the type "text/ng-template"?

I am currently working with the following code: <script id="templates/orderdetails.html" type="text/ng-template"> <ion-view view-title="OrderDetails"> <ion-content class="padding"> <p>Here I want to displ ...

What is the best way to locate a particular item in the JSON file for Our World in Data's COVID-19 Master Vaccinations dataset?

As a new coder, I am currently working on accessing specific elements within the COVID Vaccine JSON file from Our World in Data. However, I'm struggling with the syntax of my code and the structure of the JSON file. I have managed to retrieve data fr ...

I'm experiencing an issue where a function call within a Vue.js v-for directive causes the loop to continue indefinitely, but I'm unsure of the cause

Here is the template I am working with: <template> <div> <div v-for="report in reports"> <div class="map" v-bind:id="mapID = report.started.toUpperCase()" v-text="report.started"> {{hello(mapID)}} </div& ...

Implementing the Context API with React Router: using version '^5.2.0' of react-router-dom and version '17.0.2' of React

I am currently struggling to retrieve the user value from my Header component using the Context API, but unfortunately it is returning as undefined. Below is my code snippet. import React, { createContext, useEffect, useState } from "react"; exp ...

What causes CSS animations to suddenly halt?

Recently, I've been delving into the world of CSS animations and experimenting with some examples. Below is a snippet of code where two event handlers are set up for elements, both manipulating the animation property of the same element. Initially, th ...

Simplify code by eliminating uuid references

Greetings! I am currently working with some code that is generated within a JSP tag and utilizes the jQuery data function to connect data with a div element. In order to link the jQuery script with the div on the webpage, I have employed a UUID. However, ...

Struggling to execute the horizontal scrollbar plugin

I came across a fantastic color swatch plugin that I'm using, you can find it here. This plugin defines a custom Vue element which is pretty neat. In addition, I followed this example to implement a JavaScript-based scrollbar for my project. Here&ap ...

Extracting certain elements from a text: a beginner's guide

I am currently developing a task manager that includes a feature to generate a PDF file using jsPDF. I am facing the challenge of extracting specific attributes from a string in order to print them as text utilizing jsPDF. The provided string is: [{" ...

Revamping JavaScript Code for Better Performance

I've been working on a lot of code in the backend section of my website, mainly dealing with CRUD operations using AJAX calls. Do you have any suggestions on how I can refactor these functions into more generic ones or possibly create classes instead ...

The jQuery dialog function is not recognized

Based on the guidance provided in this resource: Resolving the issue with Jquery dialog not being recognized as a function Incorporated jQuery into my Electron-React-Typescript-Webpack application by implementing the following: import jQuery from 'jq ...

Double-click required to toggle button

Here is the code snippet for controlling an LED using a web page. The script, linked to Python, effectively controls the LED. However, there is an issue where the button toggles to the right side (ON position) only after a double click. Upon first click ...

Using React Quill JS and looking to log to the console when a change handler is triggered?

As I dive into the world of web development, I am currently working on crafting a blog dashboard. For the text editor, I've opted to use React Quill. While following the documentation, I came across a tutorial that includes an 'on change' ha ...

Is the canvas refusing to disappear?

My HTML5 Canvas element is not disappearing as expected. I wrote a timer function to hide the element when the timer hits 0. I tested this using an alert flag and it worked perfectly. Problem: if (TotalSeconds <= 0) { ctx.clearRect(0, 0, canvas.w ...

Validation of Checkboxes if Duplicable

I am currently working on form validation and have encountered an issue with multiple checkboxes. The first checkbox validates properly, but duplicates do not. Any help would be greatly appreciated. I understand that the code is not very efficient, but I ...

The AngularJS alert success message does not display the success div immediately after the function returns a successful response

Here is the HTML code snippet for users to input their email address and student ID: <div id="statusScope" class="pos-rel" style="margin:0 auto 50px;" ng-controller="statusController"> <form class="form-inline text-center" action=""> < ...

Encountering the error message "Module 'request' not found" despite the fact that I've already included the request module

I'm currently facing an issue with my Cloud Function that involves using the request library. After installing the request package using npm install request, I noticed it's located in the node_modules directory, just like all the other packages: ...

How can one effectively analyze a web page using client-side techniques to extract a vast number of words?

Is there a way to automatically transform keywords into links on a webpage when a specific script tag is added? I have around 25,000 keywords and I'm looking for the most efficient method to achieve this. I've attempted using basic JavaScript wi ...

Strategies for concealing and revealing content within dynamically loaded AJAX data

I am attempting to show and hide data that is loaded using Ajax. $.ajax({ type: "POST", url: "/swip.php", data: {pid:sldnxtpst,sldnu:sldnu}, success: function(result) { $('.swip').prepend(result); } }); This data gets ...