Javascript image rollover - need captions, how do I add them? - javascript

I'm using javascript to make a sort of vacation slideshow, where the main image changes depending on what link you're hovering over. I'm still new to javascript, and have spent the last two hours trying to figure out how to get the image to now display a caption underneath, I'd really love some help.
This is my js file:
var canadaOver = new Image();
canadaOver.src = 'images/canada.jpg';
var italyOver = new Image();
italyOver.src = 'images/italy.jpg';
var ukraineOver = new Image();
ukraineOver.src = 'images/ukraine.jpg';
var japanOver = new Image();
japanOver.src = 'images/japan.jpg';
var icelandOver = new Image();
icelandOver.src = 'images/iceland.jpg';
document.getElementById("canada").onmouseover = doMouseOver;
document.getElementById("italy").onmouseover = doMouseOver;
document.getElementById("ukraine").onmouseover = doMouseOver;
document.getElementById("japan").onmouseover = doMouseOver;
document.getElementById("iceland").onmouseover = doMouseOver;
function doMouseOver(evt) {
var anchor = evt.target || evt.srcElement;
var img = document.getElementById("destinations");
var textDiv = document.getElementById('caption');
if (anchor.id == "canada") {
img.src = canadaOver.src;
}
else if (anchor.id == "italy")
{
img.src = italyOver.src;
textDiv.innerHTML = imgText;
}
else if (anchor.id == "ukraine") {
img.src = ukraineOver.src;
textDiv.innerHTML = imgText;
}
else if (anchor.id == "japan") {
img.src = japanOver.src;
textDiv.innerHTML = imgText;
}
else if (anchor.id == "iceland") {
img.src = icelandOver.src;
textDiv.innerHTML = imgText;
}
}
My links are in a table next to the main image. I just can't figure out where the captions even go!

I think this is what you are looking for
https://jsfiddle.net/84cfy1Lf/
HTML
<body>
<section id="country-stuff">
</section>
</body>
SCRIPT
var countries = ['canada', 'italy', 'ukraine', 'japan', 'iceland'];
countries.forEach(function(country) {
var img = document.createElement('img');
img.id = country;
img.className = 'image';
img.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/0/06/CallingCodesWorld-Labeled.svg/500px-CallingCodesWorld-Labeled.svg.png' // swap for real image director: images/' + country +'.jpg';
var mouser = document.getElementById('country-stuff').appendChild(img);
mouser.addEventListener('mouseover', function(event) {
doMouseOver(event);
})
});
var caption = document.createElement('div');
caption.id = 'caption';
document.getElementById('country-stuff').appendChild(caption);
function doMouseOver(event) {
var anchor = event.target;
populateCountryText(anchor)
}
function populateCountryText(anchor) {
document.getElementById('caption').innerHTML = event.target.id;
return caption;
}
CSS
.image {
width: 150px;
}

Related

Deleting image from list

Here is my text field
<input type="file" name="noteMedia[]" multiple id="ssi-upload" />
Variables
const dT = new DataTransfer();
const fileInput = document.getElementById("ssi-upload");
I'm adding copy and paste feature, so i do this
document.onpaste = function(event){
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
const dTLocal = new DataTransfer();
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
dTLocal.items.add(blob);
fileInput.files = dTLocal.files;
reader.readAsDataURL(blob);
}
}
$("#ssi-upload").change();
i=i+1
}
and here is my #ssi-upload.change()
$("#ssi-upload").change(function(){
$("#imagePreview").html("");
var file = $(this)[0].files[0];
dT.items.add(file);
fileInput.files = dT.files;
imageIndex = 0;
Array.from(dT.items).forEach(item => {
var blob = item.getAsFile();
var image = new Image()
var reader = new FileReader();
var uri = URL.createObjectURL(blob);
var img = new Image();
img.src = uri;
var imagePreview = "<img width = '150px' height='100px' src='"+uri+"'>";
$("#imagePreview").append('<td style="text-align:center; vertical-align:middle">'+imagePreview+'<p class="text-center" align="text-center"> <a onclick="return deleteImage('+imageIndex+');" href="#"> Delete </a></p> </td>');
imageIndex = imageIndex + 1
});
});
So i want to have two ways to adding file, copy paste and default way from the input field. So, the problem is when i'm trying to delete the item deleteImage
function deleteImage(index){
const fileListArr = Array.from(fileInput.files)
fileListArr.splice(index, 1)
$("#ssi-upload").change()
}
The result is instead of remove file it is adding another file. So, how can i fix it ?
JSFiddle
Remove $("#ssi-upload").change() and add class to td like img-preview and pass this params to deleteImage so you can access that element. check the snippet below.
const dT = new DataTransfer();
const fileInput = document.getElementById("ssi-upload");
var i = 0;
let imageIndex = 0;
document.onpaste = function(event){
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
const dTLocal = new DataTransfer();
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
dTLocal.items.add(blob);
fileInput.files = dTLocal.files;
reader.readAsDataURL(blob);
}
}
$("#ssi-upload").change();
i=i+1
}
$("#ssi-upload").change(function(){
$("#imagePreview").html("");
var file = $(this)[0].files[0];
dT.items.add(file);
fileInput.files = dT.files;
imageIndex = 0;
Array.from(dT.items).forEach(item => {
var blob = item.getAsFile();
var image = new Image()
var reader = new FileReader();
var uri = URL.createObjectURL(blob);
var img = new Image();
img.src = uri;
var imagePreview = "<img width = '150px' height='100px' src='"+uri+"'>";
$("#imagePreview").append('<td class="img-preview" style="text-align:center; vertical-align:middle">'+imagePreview+'<p class="text-center" align="text-center"> <a onclick="return deleteImage('+imageIndex+',this);" href="#"> Delete </a></p> </td>');
imageIndex = imageIndex + 1
});
});
function deleteImage(index,obj){
const fileListArr = Array.from(fileInput.files)
fileListArr.splice(index, 1);
console.log(fileListArr);
$(obj).closest('.img-preview').remove();
//$("#ssi-upload").change()
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="noteMedia[]" multiple id="ssi-upload" />
<table class="table" id="imagePreview"><tbody></tbody></table>

Add style to a javascript variable

I got this code from a website and applied to my code:
window.onload = function () {
var fileUpload = document.getElementById("fileupload");
fileUpload.onchange = function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = document.getElementById("dvpreview");
dvPreview.innerHTML = "";
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png)$/;
for (var i = 0; i < fileUpload.files.length; i++) {
var file = fileUpload.files[i];
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("IMG");
img.width="300";
img.height ="300";
img.src = e.target.result;
dvPreview.appendChild(img);
}
reader.readAsDataURL(file);
} else {
alert(file.name + " is not a valid image file.");
dvPreview.innerHTML = "";
return false;
}
}
}
}
};
It works properly, but I want some more style to be added to my code. Specially the padding and the object-fit css properties.
I tried to run:
img.objectFit="cover";
img.style.objectFit="cover";
img.css("object-fit","cover");
and a lot more possibilities that i could search and apply, but any of those worked out.
What is the right way to make this work?
var img = document.createElement('img');
img.width = '300';
img.height = '300';
img.style.padding = '20px';
img.style.objectFit = 'fill';
document.body.appendChild(img);

how to see the images on user end from screenshot encoded into base64 from client side

This is the screen shot clicked and image is encoded to base64 string, as this is taken on client location now i want to access the same on my location so i am not able to see the images in it
The function i am using is generate() on click of a button
enter link description here this link contains base64 encoded string.
function screenshotPage() {
urlsToAbsolute(document.images);
urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']"));
var screenshot = document.documentElement.cloneNode(true);
var b = document.createElement('base');
b.href = document.location.protocol + '//' + location.host;
var head = screenshot.querySelector('head');
head.insertBefore(b, head.firstChild);
screenshot.style.pointerEvents = 'none';
screenshot.style.overflow = 'hidden';
screenshot.style.webkitUserSelect = 'none';
screenshot.style.mozUserSelect = 'none';
screenshot.style.msUserSelect = 'none';
screenshot.style.oUserSelect = 'none';
screenshot.style.userSelect = 'none';
screenshot.dataset.scrollX = window.scrollX;
screenshot.dataset.scrollY = window.scrollY;
var script = document.createElement('script');
script.textContent = '(' + addOnPageLoad_.toString() + ')();';
screenshot.querySelector('body').appendChild(script);
var blob = new Blob([screenshot.outerHTML], {
type: 'text/html'
});
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
base64data = reader.result;
};
if(base64data)
{
data = base64data.substring(base64data.indexOf(",")+1, base64data.length);
text = data+space;
arr.push(text);
}
/*else{
alert("No image recieved /n Please press screenshot button");
}*/
return blob;
}
function addOnPageLoad_() {
window.addEventListener('DOMContentLoaded', function (e) {
var scrollX = document.documentElement.dataset.scrollX || 0;
var scrollY = document.documentElement.dataset.scrollY || 0;
window.scrollTo(scrollX, scrollY);
});
}
function generate() {
window.URL = window.URL || window.webkitURL;
window.open(window.URL.createObjectURL(screenshotPage()));
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);

My function() won't run?

With this function I am trying to show a lightbulb that switches on and off once the user clicks it.
(function () {
var FavData, ImageData, create_zip, fav, favData;
window.imageData = [];
saveButton = document.createElement("save_button");
saveButton.innerHTML = "save_button";
saveButton.onclick = function () {
var image = document.getElementById('save_button');
if (image.src.match("http://www.w3schools.com/js/pic_bulbon.gif")) {
image.src = "http://www.w3schools.com/js/pic_bulboff.gif";
} else {
image.src = "http://www.w3schools.com/js/pic_bulbon.gif";
}
};
}).call(this);
And my html:
<button id="save_button"><img src="image" width="100" height="180"></button>
with the id "save_button".
There are a few issue with your code. You are not creating element using a tag. After that you are not appending it to the body. And on the button click you have to take the image id to get the source and not the button.
Here is the fiddle of a working functionality.
http://jsfiddle.net/swaprks/9vyauhvf/
(function () {
var FavData, ImageData, create_zip, fav, favData;
window.imageData = [];
saveButton = document.createElement("button");
saveButton.id = "save_button"
img = document.createElement("img");
img.src = "http://www.w3schools.com/js/pic_bulbon.gif";
img.id = "save-btn-img";
saveButton.appendChild(img);
document.body.appendChild(saveButton);
saveButton.onclick = function () {
var image = document.getElementById('save-btn-img');
if (image.src.match("http://www.w3schools.com/js/pic_bulbon.gif")) {
image.src = "http://www.w3schools.com/js/pic_bulboff.gif";
} else {
image.src = "http://www.w3schools.com/js/pic_bulbon.gif";
}
};
}).call(this);

Drag&drop and rendering thumbnails

I'm trying to make drag n' drop upload file in JS. I've written code as follow:
<div id="drop_zone">
<div style="clear: both"></div>
</div>
<output id="list"></output>
<script type="text/javascript">
var Vector = function() {
var _array = [];
this.add = function(item) {
_array.push(item);
};
this.delete = function(index) {
_array.splice(index, 1);
};
this.foreach = function(callback) {
for(i=0; i<_array.length; i++) {
callback(_array[i]);
}
};
this.length = function() {
return _array.length;
};
this.clear = function() {
_array = [];
};
};
var Snap = function(args) {
this.name = args.name || null;
this.type = args.type || null;
this.size = args.size || null;
this.modified = args.modified || null;
this.source = args.source || null;
}
var images = new Vector();
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files;
if(files.length != 0) {
for(var i=0, f; f = files[i]; i++) {
var image = new Snap({
name : escape(f.name),
type : f.type||'n/a',
size : f.size,
modified : f.lastModifiedDate ? f.lastModifiedDate.toLocaleString() : 'n/a'
});
var file = files[i];
var filereader = new FileReader;
filereader.onload = function(e) {
image.source = this.result;
};
filereader.readAsDataURL(file);
images.add(image);
}
}
alert(images.length());
render();
}
function render() {
var list = document.getElementById('list');
images.foreach(function(elem) {
var div = document.createElement('div');
var divtext = elem.name + '(<i>' + elem.type + '</i>), ' + elem.size + ' <small>[' + elem.modified + ']</small>';
div.innerHTML = divtext;
list.appendChild(div);
var img = document.createElement('img');
img.src = elem.source;
document.getElementById('drop_zone').appendChild(img);
});
}
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy';
}
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
</script>
It's not working as I wish.
This view is after I drag image first time. images.length = 1
This view is after I drag image second time. images.length actually = 2, not 3, so Vector images works as it is supposed to work.
View after third dragging, one and the same image. images.length = 3, not 6, so when it comes to Vector, it's ok.
I haven't no idea how to make it works.
Thanks in advance.

Categories