JavaScript: utilizing 'this' and onClick events

Recently, I created a basic slideshow with 4 images where upon clicking, the selected image displays in a larger div box. The functionality is quite straightforward, but if you have any queries, feel free to ask. As of now, with only 4 images in the slideshow, the current code suffices. However, what if there were over 100 pictures? In that case, duplicating and pasting the javascript function for each onclick event would not be an ideal solution in terms of cleanliness. Hence, my query revolves around how to modify the javascript so that clicking on any image automatically displays it in the larger container, making the overall code more streamlined. Thank you.

http://jsfiddle.net/jzhang172/p3Lg96p8/

function clickFunction(){
  document.getElementById("big").style.backgroundImage="url('http://assets22.pokemon.com/assets/cms2/img/pokedex/full/007.png')";
}

function clickFunction2(){
  document.getElementById("big").style.backgroundImage="url('http://cdn.bulbagarden.net/upload/thumb/f/fb/143Snorlax.png/250px-143Snorlax.png')";
}

function clickFunction3(){
  document.getElementById("big").style.backgroundImage="url('http://img2.wikia.nocookie.net/__cb20140410200831/pokemon/images/0/02/025Pikachu_Dream.png')";
}

function clickFunction4(){
  document.getElementById("big").style.backgroundImage="url('http://pre03.deviantart.net/27f2/th/pre/f/2012/218/0/7/_004_charmander___1st_attempt_sugimori_style_by_white__flame-d59zqwh.png')";
}
#container{
border:solid 2px;
width:1100px;
height:600px;
   position:relative;
   overflow:hidden;
}

#big{
border:solid 2px;
border-color:blue;
height:350px;
background:gray;
background-repeat:no-repeat;
background-position:center;
}

.slides{
text-align:center;
margin-top:30px;
border: solid 2px red;
height:200px;

}

.thumb{
border:solid 2px green;
width:260px;
height:100%;
margin:0px;
display:inline-block;
}

.thumb img{
width:100%;
height:100%;
}

.thumb:hover{
border:solid 4px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>MySlide</title>

<body>

<div id="container">
Container
     <div id="big">
     big
     </div>

     <div class="slides">

      <div class="thumb one" onclick="clickFunction()">
      <img src="http://assets22.pokemon.com/assets/cms2/img/pokedex/full/007.png">
      </div>
      <div class="thumb 2"onclick="clickFunction2()">
      <img src="http://cdn.bulbagarden.net/upload/thumb/f/fb/143Snorlax.png/250px-143Snorlax.png">
      </div>
      <div class="thumb 3"onclick="clickFunction3()">
      <img src="http://img2.wikia.nocookie.net/__cb20140410200831/pokemon/images/0/02/025Pikachu_Dream.png">
      </div>
      <div class="thumb 4"onclick="clickFunction4()">
      <img src="http://pre03.deviantart.net/27f2/th/pre/f/2012/218/0/7/_004_charmander___1st_attempt_sugimori_style_by_white__flame-d59zqwh.png">
      </div>
</body>

Answer №1

Check out this more refined method using an array of different images:

var images = [
    "http://images.example.com/first-image.png",
    "http://photos.example.net/second-image.jpg",
    "http://pics.example.org/third-image.gif",
    "http://graphics.example.edu/fourth-image.bmp"
];

function switchImage(number) {
    document.getElementById("display").style.backgroundImage = "url('" + images[number] + "')";
}

You can then call switchImage(0), switchImage(1), switchImage(2), etc. to change the image when your div is clicked.

If you prefer a more automated approach, you can do the following:

var thumbnails = document.getElementsByClassName("thumbnail");
for (var j = 0; j < thumbnails.length; j++) {
    thumbnails[j].onclick = (function(idx){
        return function() {
            document.getElementById("display").style.backgroundImage = "url('" + images[idx] + "')"
        }
    })(j);
}

Answer №2

To include the URL as a parameter in the click event, modify the onclick function like this:

function changeBackground(url) {
  document.getElementById("mainImage").style.backgroundImage = "url('" + url + "')";
}

Then use it in your HTML code as shown below:

<div class="thumbnail" onclick="changeBackground('http://example.com/image.jpg')">
    <img src="http://example.com/image.jpg">
</div>

Answer №3

View this live demo: http://example.com/demo

This piece of code extracts the source directly from the image that is clicked and then sets it as the background for the #big container

$('img').click(function() {

var imgSource = $(this).prop('src')

$('#big').css({
    backgroundImage : 'url("'+imgSource+'")'
})

})

Answer №4

Given that your functions are identical except for their URLs, it would be wise to implement a parameter system. One option is to pass the URLs as parameters, while the other involves storing all URLs in an array and passing an integer to specify the desired one.

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

Using Node.js and Typescript to bring in external modules from

Attempting to generate a random integer between 1 and 6 using the 'random' library. Here's what I have coded so far: import random from 'random' function rollDice(min:number, max:number) { return Math.floor(Math.random() * (ma ...

The functionality of Directive hinges on the use of a template

I am exploring a more web-component approach to using Angular. As part of this, I have developed an http-request directive with url and response attributes. The implementation is successful, but I find that my directive relies on a template unnecessarily. ...

What is the best way to save a file retrieved from the server through an Ajax request?

I've implemented a download feature in my application. When a user clicks a button, it triggers an ajax call to generate a CSV file with all the displayed information for download. Although I have successfully created the CSV file on the server-side, ...

What is the best way to retrieve the chosen option when clicking or changing using jQuery?

CSS <form name='category_filter' action='/jobseek/search_jobs/' method='get'> <select id="id_category" class="" name="category"> <option value="" selected="selected">All</option> <option v ...

Does this function only function on a singular div?

I need some help! I'm having trouble getting a function to trigger on the divs below the initial one. Any advice? ...

"The use of Node.js and Express.js in handling HTTP requests and responses

I am intrigued and eager to dive deep into the request and response cycle of backend development. Here's my query: I have a node.js express framework up and running. The app is launched and all functions are primed and ready for requests. app.use(&a ...

Checking for a particular element's existence in an array using jQuery

Is there a way to verify the presence of the var element in the array sites? var sites = array['test','about','try']; var element = 'other'; ...

Removing the 'div' tag using jQuery in CodeIgniter

I need assistance in removing the added item. $(document).ready(function() { $("#appendex0").click(function() { $(".divcls0").append('<div class="col-sm-10 col-sm-offset-1"><div class="col-sm-3 col-sm-offset-1"><div class="form ...

Transforming objects into nested structures

After making a JSON call, I received the following JSON Object: [ { "feeding_id": 14, "supp_name": "Test 1", "supp_weight": 20000, }, { "feeding_id": 14, "supp_name": "Test 2", "supp_weight": 100 ...

In search of a JavaScript library that can help format strings to meet the requirements of JSON formatting

Utilizing jQuery ajax, I am transmitting updates from the client's browser to my server. However, I have noticed that there are certain characters not supported by JSON that require an additional "\" in front of each one to be properly sent. The ...

Remove data from Firebase that is older than two hours

I need to implement a solution to automatically delete data that is older than two hours. Currently, I am iterating through all the data on the client-side and deleting outdated entries. However, this approach triggers the db.on('value') function ...

javascript: update hidden field if date is past January 15th

Having a bit of trouble with this one after a full day! The form contains a hidden field called 'grant_cycle'. If the form is submitted after January 15th, it should have the value 'Spring, [year]', or if after July 15th, it should be ...

What could be preventing me from exporting and applying my custom JavaScript styles?

This is my primary class import React, { Component } from 'react'; import { withStyles } from '@material-ui/core/styles'; import styles from './FoodStyles'; class Food extends Component { render () { return ( & ...

Using a function with a parameter as an argument in an event handler

Imagine you have the code snippet below: $('#from').focus(listExpand(1)); $('#to').focus(listExpand(3)); I am facing an issue as the code is not behaving as expected. I believe the problem lies in passing a function result instead of ...

Inconsistent submission of forms across different domains

I have two domains, A and B. Domain A hosts a form at A/inquire that sends a post request to B/form-submission. Domain B accepts the POST request at B/form-submission and then redirects to A/thankyou. An interesting aspect is that Domain A displays the f ...

Placing one element beside another element

I am facing an issue with my layout where I have a list taking up 100% of the height and next to it, I am attempting to place an image box. Here is the fiddle link for reference: https://jsfiddle.net/wrdvkgyj/ Even after setting my image container to inl ...

Tips for aligning text in the middle of a customizable and adjustable button with the use of only Bootstrap 4

I am encountering an issue with button text alignment. After customizing the width and height of a button, I noticed that its text does not remain centered on certain screen sizes while in debugging mode. Html <!doctype html> <html lang="en> ...

Select multiple options with personalized text using V-select

Can anyone help me with populating a v-select component from Vuetify 1.5 with checkboxes using multiple? The issue arises when I add <template slot='item' slot-scope='{ item }'></template>. It seems that the checkboxes do no ...

Adjust the width of an element as its content dynamically shifts

I have a container that contains 6 input fields. Two of them are initially hidden (display: none), but when I click on a checkbox, these two inputs become visible (display: inline). I need the width of the container to adjust and increase when the other tw ...

Event with no refresh required

When using chat scripts, new lines can be added without reloading the page. The user's availability status can change without a postback. Similar to Facebook, a new comment can be added without reloading the page. How can an event be triggered in ASP. ...