Claude Rukamiza
Claude Rukamiza

Reputation: 109

I can't append a dynamically created div with an image from a file path using a dynamic path name

I am trying to dynamically fill a div with a changing image. I am trying to do it with a changing path name. However, whenever I looked at the html code generated for the path it does not add / even though, I have concatenated it with the rest of the file name (see attached code).

I tried to rewrite the string i was concatenating, isolating the / character.

 function displayFighterbox()
{
    alert(whoseturn.name);
    if(whoseturn.name=='firstPlayer')
    {
        $('#walunguWeapon').append('<div class="playerBox" >play</div>');
        $('#walunguWeapon').append('<div><img src:"image/'+whoseturn.weapon+'.png"></div>');
    }
    if(whoseturn.name=='secondPlayer')
    {
        $('#fanjanoWeapon').append('<div class="playerBox"> Play </div>');
        $('#fanjanoWeapon').append('<div><img src:"image/"'+whoseturn.weapon+'.png></div>');
    }
}

I expect the code to append an image after the first div (which work fine by the way). But the image does not show up due to the path not concatenating properly.

Upvotes: 2

Views: 51

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Assuming the file path itself is correct you have two issues. Firstly src:"image... needs to be src="image.... Secondly, the quotes in the HTML will be mismatched and need to be fixed.

Also note that as both sides of the condition are identical apart from the selector, you can DRY up this logic by using a ternary. In addition, a single append() call will perform better than two separate ones.

function displayFighterbox() {
  var selector = whoseturn.name == 'firstPlayer' ? '#walunguWeapon' : '#fanjanoWeapon';
  $(selector).append('<div class="playerBox">play</div><div><img src="image/' + whoseturn.weapon + '.png"></div>');
}

Upvotes: 4

Related Questions