Search code examples
javascriptjqueryhtmljsonslideshow

Dynamically change Image content using JSON file?


Essentially I want to create a JS script (using jQuery) that uses the id of a clicked <div class="box"> element, finds the corresponding "id" value in the JSON file, and then adds the "image" url value to the <div class="output-box"> element. I'm not sure whether the best way to do this would be via an <img> tag, or by changing the CSS background-image property using the jQuery code, (or another way entirely), as ideally I'd like to fade between the images as the user clicks on each box.


I have a HTML file set up as follows:

<div class="box" id="1"><h1>Box 1</h1></div>
<div class="box" id="2"><h1>Box 2</h1></div>
<div class="box" id="3"><h1>Box 3</h1></div>

<div class="output-box"></div>

And a separate JSON file:

{    
    "content" : [
        {
        "id"     : 1,
        "image"  : "img/test01.jpg"
        },        
        {
        "id"     : 2,
        "image"  : "img/test02.jpg"
        },        
        {
        "id"     : 3,
        "image"  : "img/test03.jpg"
        }        
    ]    
}

And a JS file (using jQuery), set up as follows:

$.getJSON('content.json', function (data) {

    "use strict";

    var content = data.content;


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

        //Box <div> id is obtained on click
        //Object with corresponding 'id' value from JSON file is then found
        //Image url is then used to add the image to the '.output-box' <div>

    });

});

Desired Result.

This needs to be easily scalable and work regardless of how many <div class="box"> elements are added.

Detailed answers would be appreciated, as I'm still fairly new to JS and JSON and haven't found any that exactly explain what I'm trying to achieve.

Thanks! :)


Solution

  • Here's one way to do it:

    // set a click handler on all .box elements
    $('.box').click(function () {
    
      // return the first element, if it exists, of the content array that has a matching id to the clicked .box element's id
      var c = content.find(o => o.id == this.id);
    
      // make sure there was a match
      if (c) {
        // append an image with the appropriate .src property
        $('.output-box').append("<img src='" + c.image + "'>");
      }
    });