js image code example
Example 1: how to set diferent images in html through js
<div id="x"></div>
<script>
var img = document.createElement("img");
img.src = "image.png";
var src = document.getElementById("x");
src.appendChild(img);
</script>
Example 2: js get image src
var youtubeimgsrc = document.getElementById("youtubeimg").src;
Example 3: show image javascript
HTML:
<img id="theImage" src="yourImage.png">
<a id="showImage">Show image</a>
JavaScript:
document.getElementById("showImage").onclick = function() {
document.getElementById("theImage").style.visibility = "visible";
}
CSS:
#theImage { visibility: hidden; }
Example 4: show image javascript
JS:
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
HTML:
<img id="myImageId" src="yourImage.png">
Then, your links would be:
<a href="javascript:setImageVisible('myImageId', true)">show image</a>
<a href="javascript:setImageVisible('myImageId', false)">hide image</a>
CSS:
#theImage { visibility: hidden; }
Example 5: js load img
var elements = [];
function loaded(){
console.log("you have loaded an image");
}
CreateFileFrom("your/dir/here/img.png");
function CreateFileFrom(dir){
var extension = dir.split('.').pop();
var keys = {"png":"IMG","jpg":"IMG","jpeg":"IMG",
"js":"SCRIPT","json":"SCRIPT",
"mp3":"AUDIO","wav":"AUDIO"};
var obj = document.createElement(keys[extension]) || {};
obj.src = dir;
obj.onload = (e) => {
elements.push(e.path[0]);
loaded()
}
if(keys[extension]==null){console.error("not supported media type "+extension);return;}
}