appending image with websockets to pug file

244 views Asked by At

I'm creating a small app with node.js and have stumbled upon a problem. I am trying to send an img to all users from my admin account. The problem is I can't seem to show my image through javascript appending to the div I made . Is it because I'm working with pug that it doesn't render my image?

My admin side

document.querySelector('#Function1').addEventListener("click", function (e) {
  alert('hi mom');

  primus.write({message: 'function1'});
  //console.log(id);
  e.preventDefault;
});

My client side

var image = "images/logo.png";

primus.on("data", function (data) {
  if (data.message != undefined) {
    if (data.message == 'function1') {
      document.querySelector("#functionShow").append("<img src="+image+"/>");
    } else {
      console.log('something went wrong');
    }
  }
});

This is the end result shown

welkom Hanna

<img src=images/logo.png/>

2

There are 2 answers

0
Michał Sałaciński On

Nah, it's not pug's fault, pug is innocent of this crime :)

What you're missing are quotes around "images/logo.png", it should be

var image ="images/logo.png";

primus.on("data", function (data) {
  if (data.message != undefined) {
    if (data.message == 'function1') {
      document.querySelector("#functionShow").append('<img src="'+image+'"/>');
    } else {
      console.log('something went wrong');
    }
  }
});

It's because browsers are trying to access "logo.png" as a folder now.

0
Chandrakant On

@aperçu That sadly didn't work either :(

But I did find a solution! It seems I had to create an img element and do it this way, I'm nto exactly sure why

var elem = document.createElement("img");
elem.setAttribute("src", "images/logo.png");
elem.setAttribute("alt", "logo");

var elem2 = document.createElement("img");
elem2.setAttribute("src", "images/header.png");
elem2.setAttribute("alt", "logo");

primus.on("data", function (data) {
    if(data.message != undefined) {
        if(data.message == 'function1') {
            document.querySelector("#functionShow").append(elem);
        }if(data.message == 'function2') {
            document.querySelector("#functionShow").append(elem2);
        }
        else {
            console.log('i fucked up');
        }
    }
});