Using <img src> in js?
I have the following:
var diff = maxval - ui.value; $( "#output").html( diff?"diff. of " + diff : "no diff" ); Now I would like to add an image to each, if there is a difference in value or not, that is:
var diff = maxval - ui.value; $( "#output").html( diff?"<img src='yes.png' height='50' width='50' /> diff. of " + diff : "<img src='no.png' height='50' width='50' /> no diff" ); Seeing this not work, how can I set an image for each of this output div?
You are checking based on diff , you don't want to check if it is more?
Negative numbers are evaluated to true .
Boolean(-1);//true Boolean(50);//true Boolean(-500);//true Boolean(-0.001);//true Boolean(0);//false This is how I create a new image with a diff based source attribute greater than 0. Note: I use the actual elements, so I change the src attribute instead of the string value, which seems to me to create more readable code.
var diff = maxval - ui.value; var img = new Image(); img.src = (diff > 0 ) ? "yes.png" : "no.png"; img.width = "50px"; img.height = "50px"; $( "#output").empty().append(img); Here is a completely vanilla solution, including node text:
var diff = maxval - ui.value; var img = new Image(); img.src = (diff > 0 ) ? "yes.png" : "no.png"; // assuming you mean to check positive value img.width = "50px"; img.height = "50px"; var el = document.getElementById("output"); el.appendChild(img); var text = (diff > 0) ? "diff" : "no diff"; var txt = document.createTextNode(text); el.appendChild(txt); Although the advantages of this longer code seem obvious at first, it is very easy to manipulate. I work with DOM elements directly instead of strings, I can easily add or remove attributes, change properties, clone them, etc.
I'm not sure if I understood the question correctly, if so, at least it can help you a bit:
var yes = $( "<img>").attr( {"src": 'yes.png', "height": '50', "width": '50' }); var no = $( "<img>").attr( {"src": 'no.png', "height": '50', "width": '50' }); if(diff){ $( "#output").append(yes).append('diff. of ' + diff); } else{ $( "#output").append(no).append('no diff'); } Example: http://jsfiddle.net/WKg3A/