Search code examples
javascriptjqueryajaxjsonmouseenter

use JSON variable in jQuery dynamically


I have two DIVs, #placeholder AND #imageLoad. When the user clicks on a particular thumb its larger version (thumb2) should then appear in #imageLoad DIV.

Here is the jQuery that needs to be fixed:

  $.getJSON('jsonFile.json', function(data) {
        var output="<ul>";
        for (var i in data.items) {
            output+="<li><img src=images/items/" + data.items[i].thumb + ".jpg></li>";
        }
        output+="</ul>";
        document.getElementById("placeholder").innerHTML=output;
  });


  //This is wrong!! Not working..
  $('li').on({
         mouseenter: function() {
             document.getElementById("imageLoad").innerHTML="<img src=images/items/" +
             data.items[i].thumb2 + ".jpg>";
         }
  });    

Here is the external JSON file below (jsonFile.json):

{"items":[
    {
        "id":"1",
        "thumb":"01_sm",
        "thumb2":"01_md"
    },
    {
        "id":"2",
        "thumb":"02_sm",
        "thumb2":"02_md"
    }
]}

Solution

  • $.getJSON('jsonFile.json', function(data) {
        var output="<ul>";
        for (var i = 0; i < data.items.length; i++) {
            output += "<li><img thumb2='" + data.items[i].thumb2 + "' src='images/items/" + data.items[i].thumb + ".jpg'></li>";
        }
        output += "</ul>";
        $("#placeholder").html(output);
    
        $('li').on({
            mouseenter: function() {
                $("#imageLoad").html("<img src='images/items/" + $(this).find('img').attr('thumb2') + ".jpg'>");
            }
        });   
    });