I am having problem converting image to blob and back to file, I mean when I convert image to blob and display on the page, chose which I want to keep and which I want to remove and after try to convert back to file and append to form data, nothing gets appended to formData and file type and size on new files from blob images are different, how can I change that? Thank you
$(document).on('click', '#addProduct', function(e) {
e.preventDefault();
var arr = [];
for(var q=0; q<$('.image-buttons').length; q++) {
var blob = $('.image-buttons').children('img').attr('src');
var fileOfBlob = new File([blob], 'image'+q);
arr.push(fileOfBlob);
}
if(arr.length < 4 && arr.length > 0){
var formData = new FormData();
$.each(arr, function(i, file) {
formData.append('images', file);
console.log(file);
});
console.log(formData);
return false;
}
});
$(document).on('change', '#images', function() {
var reg = /\.(gif|jpg|png|GIF|JPG|PNG|jpeg|JPEG)$/i;
var imageNameArray = [];
for(var j = 0; j<$("#images")[0].files.length; j++) {
if(!$("#images")[0].files[j].name.match(reg)){
imageNameArray.push($("#images")[0].files[j].name);
}
}
if(imageNameArray.length === 0 && $("#images")[0].size<2097152){
for(var e=0; e<$("#images")[0].files.length; e++) {
$('.img-button-holder').append('<div class="image-buttons"><img src="'+window.URL.createObjectURL($("#images")[0].files[e])+'"><div class="img-tools"><i class="fa fa-angle-double-left" aria-hidden="true"></i><i class="fa fa-angle-double-right" aria-hidden="true"></i><i class="fa fa-times removeImg" aria-hidden="true"></i></div></div>');
}
$('.image-display').append('<img src="'+window.URL.createObjectURL($("#images")[0].files[0])+'">');
}
});
$(document).on('click', '.image-buttons', function() {
var this_img = $(this).children('img').attr('src');
$('.image-buttons').css('border','1px solid #e0e0e0');
$(this).css('border','2px solid red');
$('.image-display').children('img').attr('src', this_img);
});
$(document).on('click', '.img-tools > .fa', function() {
var this_el = $(this).parent().parent();
if($(this).hasClass('removeImg')){
$(this_el).remove();
}else if($(this).hasClass('fa-angle-double-left')) {
var prev = $(this_el).prev();
$(this_el).insertBefore(prev);
}else if($(this).hasClass('fa-angle-double-right')) {
var next = $(this_el).next();
$(this_el).insertAfter(next);
}
});
.addNew {
width: 100%;
height: auto;
float: left;
}
.addNew > form {
width: 40%;
float: left;
height: auto;
margin-right: 5%;
}
.addNew > .image-display {
width: 55%;
float: right;
min-height: 300px;
height: auto;
border: 1px solid #e0e0e0;
position: relative;
}
.addNew .image-buttons {
width: 30%;
height: 80px;
margin: 10px 1.5%;
border: 1px solid #e0e0e0;
float: left;
overflow: hidden;
position: relative;
}
.img-button-holder {
width: 55%;
float: right;
}
.image-buttons > img, .image-display > img {
width: 100%;
height: 100%;
min-height: 100%;
min-width: 100%;
}
.image-display > img {
width: 100%;
height: auto;
min-height: auto;
min-width: 100%;
position: absolute;
bottom: 0; left: 0;
}
.img-tools {
color: red;
font-size: 2rem;
position: absolute;
width: 100%;
height: auto;
top: 0; left: 0;
}
.img-tools > i {
float: left;
width: 30%;
margin: 5px 1.5%;
cursor: pointer;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="addNew">
<form>
<input type="file" name="images" id="images" multiple>
<button id="addProduct">Add</button>
</form>
<div class="image-display"></div>
<div class="img-button-holder"></div>
</div>
A blobURI (that you miscalled blob in your code) is just a string.
The File object you create is just that string in a text/plain file.
You don't have to convert from a File to a blobURI to a File.
Just keep the initial Files, store them in a good ol' Array, manage them from there.
Create the blobURI only to display these Files (it's really just a pointer in the memory so your document (here <img>) knows how to access the file on the user disk, and hence can't be shared).
When you need to send the files, simoly take them from the Array you did the management with.
ps: Note that depending on your back-end, you might have to append a [] at the name of your formData key.
function sendToServer() {
var formData = new FormData(),
files = fileHandler.list; // grab them directly from our manager
// it's an Array, so use Array methods
files.forEach(function(file) {
// since you are on php, to be able to append multiple items in the same field,
// you need to append '[]' at the end of your fieldName
formData.append('images[]', file);
});
// send it to your server
var xhr = new XMLHttpRequest();
xhr.open('POST', 'your_php_script');
// xhr.send(formData);
// but from SO we will just show what's inside
if (typeof formData.getAll === 'function') {
console.log(formData.getAll('images[]'));
}
}
// A basic file manager which will expose its selected files in an Array
function FileHandler(options) {
if (!options || typeof options !== 'object')
options = {};
this.options = options;
// this is really the only important part: we use an Array to store all our files
this.list = [];
this.addButton = isValidElement(options.addButton) || $('<button>', {
text: 'Add new Files'
});
// also, we use a single file input
this.input = $('<input>', $.extend(options.input || {}, {
type: 'file',
class: 'fh-input',
multiple: true,
}));
this.items_container = isValidElement(options.items_container) || $('<div>', {
class: 'fh-item-container'
});
this.preview = this.initPreview();
this.addButton.on('click', function() {
this.input.click()
}.bind(this));
this.input.on('change', this.onchange.bind(this));
this.items_container.on('click', '.fh-item .fh-remove', this.remove.bind(this));
this.items_container.on('click', '.fh-item :not(.fh-remove)', this.handleItemClick.bind(this));
this.items_container.on('load', 'img', revokeURL);
// We don't need blobURIs for anything else than loading <img> elements,
// so we can revoke them directly at load
function revokeURL(evt) {
var url = evt.currentTarget.src;
URL.revokeObjectURL(url);
}
function isValidElement(obj) {
var $obj = $(obj);
return $obj[0] && $obj[0] instanceof Element && $obj.eq(0);
}
}
FileHandler.prototype = Object.create({
add: function addFile(file) {
if (!(file instanceof Blob))
throw new TypeError('Argument 1 must be Blob or a File');
var $item = this.generateItem(file);
this.items_container.append($item);
// store it in our Array
this.list.push(file);
this.preview.show(file);
return $item;
},
remove: function removeFile(event) {
var $target = $(event.currentTarget),
$item = $target.parents('.fh-item').eq(0),
file = $item.data('fh.file'),
index = this.list.indexOf(file);
$item.remove();
if (index > -1) {
// remove it from our Array
this.list.splice(index, 1);
}
if (this.preview.current === file) {
if (this.list.length) {
var next = index <= (this.list.length - 1) ? index : 0;
this.preview.show(this.list[next]);
} else this.preview.hide();
}
},
generateItem: function generateItem(file) {
if (!(file instanceof Blob))
throw new TypeError('Argument 1 must be Blob or a File');
var $cont = $('<div>', {
class: 'fh-item'
}),
$title = $('<span>', {
text: file.name || 'unknown-file (' + file.type + ')',
class: 'fh-file_name'
}),
$btn = $('<button>', {
class: 'fh-remove',
text: 'x',
title: 'remove',
name: 'remove item'
}),
$thumb = $('<div>', {
class: 'fh-thumb'
})
// a single time blobURI
.append($('<img>', {
src: URL.createObjectURL(file)
}));
$cont.data('fh.file', file);
return $cont.append(
$title,
$btn,
$thumb
);
},
onchange: function oninputchange(evt) {
// retrieve the Files contained in our single input
var fileList = this.input[0].files;
for (var i = 0; i < fileList.length; i++) {
this.add(fileList[i]);
}
},
handleItemClick: function handleItemClick(evt) {
var $target = $(evt.currentTarget),
$item = $target.parents('.fh-item').eq(0),
file = $item.data('fh.file');
this.preview.show(file);
},
initPreview: function() {
var $cont = $('<div>', {
class: 'fh-preview'
}),
img = new Image();
return {
container: $cont.append(img),
update: function updatePreview(url) {},
show: function show(file) {
if (!(file instanceof Blob)) {
console.warn('Not a Blob', file);
throw new TypeError('Argument 1 must be Blob or a File');
}
if (this.current !== file) {
this.current = file;
img.src = URL.createObjectURL(file);
}
$cont.show();
},
hide: function hide() {
img.src = '#';
$cont.hide();
}
};
}
});
var fileHandler = new FileHandler({
input: {
accept: 'image/*'
}
});
$('body').append(
fileHandler.addButton,
$('<button>', {
text: 'send to server'
})
.on('click', sendToServer),
fileHandler.items_container,
fileHandler.preview.container,
);
.fh-item {
border: 1px solid;
display: inline-block;
min-width: 130px;
min-height: 130px;
vertical-align: middle;
}
.fh-file_name {
display: inline-block;
width: 100px;
overflow: hidden;
text-overflow: ellipsis;
margin: 2px 4px;
vertical-align: top;
}
.fh-remove {
box-shadow: none;
border: none;
float: right;
cursor: pointer;
}
.fh-remove:hover {
color: #CC0000;
}
.fh-thumb {
text-align: center;
width: 100%;
height: 100px;
}
.fh-thumb>img {
max-width: 100px;
max-height: 100px;
margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
As topic, how can I remove the quote in the picuture below or get the img element from this?
(https://i.stack.imgur.com/kdPAP.png)
I m new to javascript and start making an image slider that can pop up a window while clicked to the image.
I cloned the li object which is clicked, and try to open it in the new window, it do work but how can I get the img only without the li?
Right now i m trying to call the cloned this object with innerHTML, but it shows the img element with quote, is there any way to remove the quote?
the quote that i want to remove
first time ask a question in here, if i violate any rules in the post, i delete the post, sorry for causing any inconvenience.
Here is the code
<!DOCTYPE html>
<html>
<head>
<style>
.risuto1 {
max-width: 480px;
max-height: 270px;
margin: auto;
position: relative;
}
ul {
list-style-type: none;
margin: auto;
padding: 0;
}
.aitemu>img {
max-width: 100%;
}
.aitemu {
display: none;
position: relative;
}
.aitemu.akutibu {
display: block;
}
.risuto1>.mae,
.tsugi {
width: auto;
height: auto;
padding: 20px;
top: 102.6px;
position: absolute;
cursor: pointer;
background-color: red;
}
.risuto1>.tsugi {
left: 431.8px;
}
</style>
</head>
<body>
<script>
var risuto1 = document.createElement("div");
risuto1.classList.add("risuto1");
document.body.appendChild(risuto1);
var suraidaaitemu = document.createElement("ul");
suraidaaitemu.classList.add("suraidaaitemu");
risuto1.appendChild(suraidaaitemu);
var imejisosurisuto = ["https://pbs.twimg.com/media/CGGc3wKVEAAjmWj?format=jpg&name=medium", "https://pbs.twimg.com/media/EYCXvuzU8AEepqD?format=jpg&name=large", "https://s3-ap-northeast-1.amazonaws.com/cdn.bibi-star.jp/production/imgs/images/000/668/074/original.jpg?1626914998", "https://livedoor.blogimg.jp/rin20064/imgs/7/3/73251146.jpg", "https://www.tbs.co.jp/anime/oregairu/character/img/chara_img_02.jpg"]
//var imejirisuto=[]
for (var n = 0; n < imejisosurisuto.length; n++) {
var imeji = document.createElement("img");
imeji.src = imejisosurisuto[n];
var aitemu = document.createElement("li");
aitemu.classList.add("aitemu");
suraidaaitemu.appendChild(aitemu);
aitemu.appendChild(imeji);
aitemu.onclick=atarashivindou;
}
var akutibunasaishonoko = document.querySelector(".suraidaaitemu").firstChild;
akutibunasaishonoko.classList.add("akutibu");
var mae = document.createElement("div");
mae.classList.add("mae");
mae.innerHTML = "❮";
risuto1.appendChild(mae);
var tsugi = document.createElement("div");
tsugi.classList.add("tsugi");
tsugi.innerHTML = "❯";
risuto1.appendChild(tsugi);
var tensuu = 0;
var suraido = document.querySelector(".suraidaaitemu").children;
var gokeisuraido = suraido.length;
tsugi.onclick = function () {
Tsugi("Tsugi");
}
mae.onclick = function () {
Tsugi("Mae");
}
function Tsugi(houkou) {
if (houkou == "Tsugi") {
tensuu++;
if (tensuu == gokeisuraido) {
tensuu = 0;
}
}
else {
if (tensuu == 0) {
tensuu = gokeisuraido - 1;
}
else {
tensuu--;
}
}
for (var i = 0; i < suraido.length; i++) {
suraido[i].classList.remove("akutibu");
}
suraido[tensuu].classList.add("akutibu");
}
function atarashivindou(){
var Atarashivindou = window.open("", "_blank", "width: 1000px, max-height: 562.5px");
var kakudaigazou=document.createElement("div");
kakudaigazou.classList.add("kakudaigazou");
Atarashivindou.document.body.appendChild(kakudaigazou);
var koronaitemu=this.cloneNode(true);
var koronimeji=koronaitemu.innerHTML;
kakudaigazou.append(koronimeji);
}
</script>
</body>
.innerHTML is a string. You don't want to append a string, but the element. So change this:
var koronaitemu=this.cloneNode(true);
var koronimeji=koronaitemu.innerHTML;
kakudaigazou.append(koronimeji);
...to this:
var koronimeji=this.querySelector("img").cloneNode();
kakudaigazou.append(koronimeji);
I'm trying to create a quiz that tests users awareness of real and fake emails. What I want to do is have the question displayed at the top saying "Real or Fake", then have an image displayed underneath which the user needs to look at to decided if it's real or fake. There are two buttons, real and fake, and regardless of whether they choose the right answer I want to swap the original image with annotated version - showing how users could spot that it was fake or real.
But I'm not sure how to show the annotated version once the answer has been submitted. Could someone help?
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions here
var questions = [
new Question("<img src= 'netflix_fake.jpg' />", ["Real", "Fake"], "Fake"),
new Question("<img src= 'dropbox_real.jpg' />", ["Real", "Fake"], "Real"),
new Question("<img src= 'gov_real.jpg' />", ["Real", "Fake"], "Real"),
new Question("<img src= 'paypal_fake.jpg' />", ["Real", "Fake"], "Fake"),
new Question("<img src= 'gmail.jpg' />", ["Real", "Fake"], "Fake")
];
//create quiz
var quiz = new Quiz(questions);
// display
populate();
body {
background-color: #538a70;
}
.grid {
width: 600px;
height: 500px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border: 2px solid #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
font-size: 60px;
text-align: center;
color: #000000;
padding: 2px 0px;
}
#score {
color: #000000;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 30px;
color: #000000;
}
.buttons {
margin-top: 30px;
}
#btn0,
#btn1,
#btn2,
#btn3 {
background-color: #a0a0a0;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #00994d;
}
#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
<div class="grid">
<div id="quiz">
<h1>Can you spot the fake email?</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
</div>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
When user clicks button I trigger class and I add it second name, on second I have written to get swapped, I wrote you basically full project, and please read the whole comments, to understand logic
//Calling Elements from DOM
const button = document.querySelectorAll(".check");
const images = document.querySelectorAll(".image");
const answer = document.querySelector("h1");
//Declaring variable to randomly insert any object there to insert source in DOM Image sources
let PreparedPhotos;
//Our Images Sources and With them are its fake or not
//fake: true - yes its fake
//fake: false - no its real
const image = [
[
{
src:
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/1200px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg",
fake: true
},
{
src:
"http://graphics8.nytimes.com/images/2012/04/13/world/europe/mona-lisa-like-new-images/mona-lisa-like-new-images-custom4-v3.jpg",
fake: false
}
],
[
{
src:
"https://cdn.shopify.com/s/files/1/0849/4704/files/Creacion_de_Adan__Miguel_Angel_f5adb235-bfa8-4caa-8ffb-c5328cbad953_grande.jpg?12799626327330268216",
fake: false
},
{
src:
"https://cdn.shopify.com/s/files/1/0849/4704/files/First-image_Fb-size_grande.jpg?10773543754915177139",
fake: true
}
]
];
//Genrating Random Photo on HTML
function setRandomPhoto() {
//Random Number which will be length of our array of Object
//if you array includes 20 object it will generate random number
// 0 - 19
const randomNumber = Math.floor(Math.random() * image.length);
//Decalaring our already set variable as Array Object
PreparedPhoto = image[randomNumber];
//Our first DOM Image is Variables first object source
images[0].src = PreparedPhoto[0].src;
//and next image is next object source
images[1].src = PreparedPhoto[1].src;
}
//when windows successfully loads, up function runs
window.addEventListener("load", () => {
setRandomPhoto();
});
//buttons click
//forEach is High Order method, basically this is for Loop but when you want to
//trigger click use forEach - (e) is single button whic will be clicked
button.forEach((e) => {
e.addEventListener("click", () => {
//decalring variable before using it
let filtered;
//finding from our DOM image source if in our long array exists
//same string or not as Image.src
//if it exists filtered variable get declared with that found obect
for (let i = 0; i < image.length; i++) {
for (let k = 0; k < 2; k++) {
if (image[i][k].src === images[0].src) {
filtered = image[i][k];
}
}
}
//basic if else statement, if clicked button is Fake and image is true
//it outputs You are correct
//if clicked button is Real and Image is false it outputs Correct
//Else its false
//Our image checking comes from filtered variable
if (e.innerText === "Fake" && filtered.fake === true) {
answer.innerText = "You Are Correct";
images.forEach((image) => {
image.classList.toggle("hidden");
});
} else if (e.innerText === "Real" && filtered.fake === false) {
answer.innerText = "You Are Correct";
images.forEach((image) => {
image.classList.toggle("hidden");
});
} else {
answer.innerHTML = "You are Wrong";
images.forEach((image) => {
image.classList.toggle("hidden");
});
}
});
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100%;
min-height: 100vh;
display: flex;
justify-content: space-around;
align-items: center;
flex-direction: column;
}
.image-fluid {
display: flex;
}
.image-fluid .image {
width: 200px;
margin: 0 10px;
transition: 0.5s;
}
.image-fluid .image:nth-child(1).hidden {
transform: translateX(110px);
}
.image-fluid .image:nth-child(2).hidden {
transform: translateX(-110px);
}
<div class="container">
<div class="image-fluid">
<img src="" class="image hidden">
<img src="" class="image hidden">
</div>
<div class="button-fluid">
<button class="check">Fake</button>
<button class="check">Real</button>
</div>
</div>
<h1></h1>
I am coding in Joomla in which I have self synchronized three audio tracks i.e when one of them starts on the web page the other stop and below is the JS code for the same;
<script type="text/javascript">
function _(id) {
return document.getElementById(id);
}
//function Download(url) {
//document.getElementById('my_iframe').src = url;
//};
function audioApp() {
var audio = new Audio();
var audio_folder = "/images/audios/how-to-meditate/relaxation/";
var audio_ext = ".mp3";
var audio_index = 1;
var is_playing = false;
var playingtrack;
var trackbox = _("trackbox");
var tracks = {
"track1": ["Relaxation in the Forest", "relaxation-in-the-forest"],
"track2": ["Relaxation of the Muscles", "relaxation-of-the-muscles"],
"track3": ["Relaxation with the Breath", "relaxation-with-the-breath"]
};
for (var track in tracks) {
var tb = document.createElement("div");
var pb = document.createElement("button");
//var dn = document.createElement("button");
var tn = document.createElement("div");
tb.className = "trackbar";
pb.className = "playbutton";
//dn.className = "download";
tn.className = "trackname";
tn.innerHTML = tracks[track][0];
pb.id = tracks[track][1];
tb.appendChild(pb);
pb.addEventListener("click", switchTrack);
tb.appendChild(tn);
trackbox.appendChild(tb);
audio_index++;
}
audio.addEventListener("ended", function() {
_(playingtrack).style.background = "url(images/icons/play.JPG)";
playingtrack = "";
is_playing = false;
});
function switchTrack(event) {
if (is_playing) {
if (playingtrack != event.target.id) {
is_playing = true;
_(playingtrack).style.background = "url(images/icons/play.JPG)";
event.target.style.background = "url(images/icons/pause.JPG)";
audio.src = audio_folder + event.target.id + audio_ext;
audio.play();
} else {
audio.pause();
is_playing = false;
event.target.style.background = "url(images/icons/play.JPG)";
}
} else {
is_playing = true;
event.target.style.background = "url(images/icons/pause.JPG)";
if (playingtrack != event.target.id) {
audio.src = audio_folder + event.target.id + audio_ext;
}
audio.play();
}
playingtrack = event.target.id;
}
}
window.addEventListener("load", audioApp);
</script>
Below is the Styling;
<style scoped="scoped" type="text/css">
.trackbar {
background: #FFF;
height: 50px;
font-family: "Arial";
}
.trackbar:nth-child(even) {
background: #FFF;
}
.playbutton {
opacity: .8;
display: block;
float: left;
width: 40px;
height: 40px;
margin: 0px 50px 0px 50px;
background: url(images/icons/play.JPG) no-repeat;
border: none;
cursor: pointer;
outline: none;
}
.playbutton:hover {
opacity: 1;
}
.trackname {
float: left;
color: #000;
margin: 12px 400px 0px 14px;
font-size: 20px;
}
And the html code is;
<div id="trackbox"> </div>
Having achieved this I want to place a download icon besides every mp3 which allows me to download the track, I have the link to download the file and it is placed in the media (Content) of Joomla and also I want a icon to be placed which will trigger the download onClick.
Is there a JS script code available with which I can implement the same.
This is what solved the issue;
<input alt="Submit" src="images/icons/download.jpg" type="image" onclick="document.getElementById('anything').click()" />
I have done this working fiddle:
HTML
<div id="container">
<div id="input_container">
<label for="increment_t">Set t-increment value (default 0.1):</label>
<input id="increment_t" type="number" min="0" max="1" step="0.1" value="0.1" />
</div>
<br />
<div id="generator_container">
<a id="downloadlink" download="outfile.txt">Download</a>
<button id="create_link">Export output</button>
</div>
</div>
CSS
#container {
position: absolute;
display: block;
left: 0;
top: 0;
padding: 10px 10px; /* (top-bottom) (left-right) */
z-index: 1;
}
#input_container {
display: block;
float: left;
margin-bottom: 10px;
}
#increment_t {
max-width: 50px;
}
#generator_container {
display: block;
float: right;
}
#downloadlink {
display: none;
margin-right: 10px;
}
#create_link {
float: right;
}
JavaScript
(function () {
var t_values;
var t_values_list = [];
for ( var t=0; t<=1; t+=0.1 ){
t_values = t.toFixed(1);
t_values_list.push(t_values);
}
var textFile = null;
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create_link = document.getElementById('create_link');
create_link.addEventListener('click', function () {
alert(t_values_list);
var link = document.getElementById('downloadlink');
link.href = makeTextFile(t_values_list.join('\n'));
link.style.display = 'inline-block';
}, false);
})();
but I want to set the increment value for the "t" variable (i.e. 0.1, in the for-loop) taking it from the input area. I tried in this way:
JavaScript
(function () {
var t_values;
var t_values_list = [];
alert(document.getElementById("increment_t").value); // test to get the t value, to use it in the following loop for
for ( var t=0, increment_t=document.getElementById("increment_t").value; t<=1; t+=increment_t ){
t_values = t.toFixed(1);
t_values_list.push(t_values);
}
var textFile = null;
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create_link = document.getElementById('create_link');
create_link.addEventListener('click', function () {
alert(t_values_list);
var link = document.getElementById('downloadlink');
link.href = makeTextFile(t_values_list.join('\n'));
link.style.display = 'inline-block';
}, false);
})();
but It doesn't work. Thanks for your help
If you getting numbers from somewhere else in javascript...always parse them. parseInt(..., 10) or in your example: parseFloat
I created a plug-in to display a Metro MessageBar and it works great. I was asked to support callbacks and added some code to the fadeIn functionality for this purpose.
For some reason, the callback shows as a valid function, but doesn't call?
HERE IS THE CONSOLE MESSAGE I AM GETTING:
this.trigger is not a function
...any help is appreciated.
THIS IS HOW TO USE THE PLUG-IN:
this.showSubmitMessage = function () {
var options = {
message: "This is a test.",
messageType: "information"
};
// self.btnSubmit.click IS a valid function!!! Use your own if you want.
nalco.es.rk.globals.messageBarManager.display(options, self.btnSubmit.click);
};
THIS IS THE OFFENDING AREA-OF-CODE IN THE PLUG-IN:
this.fadeIn = function (element, callback) {
element.prependTo(self.container).centerToScrollTop().fadeIn(self.globals.fadeDuration, function() {
if (callback != null)
if ($.isFunction(callback))
setTimeout(function () {
callback();
}, self.globals.callbackDuration);
});
};
THIS IS THE ENTIRE USER-CONTROL PLUG-IN:
Please notice the code for the file-dependency "jquery.Extensions.js" is at the bottom of this posting.
<script src="Scripts/jQuery/Core/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="Scripts/jQuery/Core/jquery.tmpl.js" type="text/javascript"></script>
<script src="Scripts/jQuery/jquery.Extensions.js" type="text/javascript"></script>
<style type="text/css">
.messageBar { background-color: #DDDDDD; color: #666666; display: none; left: 0; padding: 15px; position: absolute; top: 0; width: 932px; z-index: 1000; }
.messageBar .content { width: 100%; }
.messageBar .content td.image { width: 70px; }
.messageBar .content td.button { width: 60px; }
.messageBar .button { margin-top: 0px; }
.messageBar .content .icon { background-repeat: no-repeat; height: 31px; overflow: hidden; width: 31px; }
.messageBar .content .message { }
.messageBar .content .image { background-repeat: no-repeat; height: 10px; overflow: hidden; width: 70px; }
.messageBar.error { background-color: #FFBABA; color: #D8000C; }
.messageBar.information { background-color: #99CCFF; color: #00529B; }
.messageBar.success { background-color: #DFF2BF; color: #4F8A10; }
.messageBar.warning { background-color: #FEEFB3; color: #9F6000; }
.messageBar.error .content .icon { background-image: url('/_layouts/images/error.png'); }
.messageBar.information .content .icon { background-image: url('/_layouts/images/info.png'); }
.messageBar.success .content .icon { background-image: url('/_layouts/images/success.png'); }
.messageBar.warning .content .icon { background-image: url('/_layouts/images/warning.png'); }
</style>
<script id="template-messageBar" type="text/html">
<div class="messageBar">
<table class="content">
<tbody>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td class="button">
<input type="button" value="Close" class="button metroButton" />
</td>
</tr>
</tbody>
</table>
</div>
</script>
<script id="template-messageBar-icon" type="text/html">
<div class="icon">
</div>
</script>
<script id="template-messageBar-message" type="text/html">
<div class="message">
${Message}
</div>
</script>
<script id="template-messageBar-image" type="text/html">
<div class="image">
</div>
</script>
<script type="text/javascript">
;nalco.es.rk.source.MessageBarManager = (function ($) {
var publicInstances = {};
publicInstances.Controller = Controller;
function Controller(options) {
var self = this;
this.messageTypes = { error: "error", information: "information", normal: null, success: "success", warning: "warning" };
this.globals = {
callbackDuration: 2000,
fadeDuration: 700,
workingImageUrl: "url('/_layouts/images/Nalco.ES.SharePoint.UI/metro-ajax-loader-blue.gif')"
};
this.defaults = {
message: "",
messageType: self.messageTypes.normal,
showIcon: false,
showWorkingImage: false
};
this.container = $('body');
this.templateMessageBarId = '#template-messageBar';
this.templateMessageBarIconId = '#template-messageBar-icon';
this.templateMessageBarMessageId = '#template-messageBar-message';
this.templateMessageBarImageId = '#template-messageBar-image';
this.selectors = { content: '.content', closeButton: '.button', root: '.messageBar' };
this.initialize = function () {
self.display(options);
};
this.display = function (options, callback) {
var empty = {};
var settings = $.extend(empty, self.defaults, $.isPlainObject(options) ? options : empty);
if (settings.messageType != null)
if (settings.messageType.length == 0)
settings.messageType = self.messageTypes.normal;
if (settings.message.length == 0)
return;
var eleMessageBar = $(self.templateMessageBarId).tmpl(empty);
var eleContent = $(self.selectors.content, eleMessageBar);
var eleCellOne = $('td:eq(0)', eleContent);
var eleCellTwo = $('td:eq(1)', eleContent);
var eleCellThree = $('td:eq(2)', eleContent);
var eleMessage = $(self.templateMessageBarMessageId).tmpl({ Message: settings.message });
var btnClose = $(self.selectors.closeButton, eleMessageBar);
if (settings.messageType != self.messageTypes.normal) {
eleMessageBar.addClass(settings.messageType);
if (settings.showIcon) {
var eleIcon = $(self.templateMessageBarIconId).tmpl(empty);
eleCellOne.css('width', '31px');
eleIcon.appendTo(eleCellOne);
}
}
eleMessage.appendTo(eleCellTwo);
btnClose.click(function () {
eleMessageBar.fadeOut(self.globals.fadeDuration, function () {
eleMessageBar.remove();
});
});
if (settings.showWorkingImage) {
var eleImage = $(self.templateMessageBarImageId).tmpl(empty);
eleCellThree.addClass('image');
eleImage.css('background-image', self.globals.workingImageUrl);
eleImage.appendTo(eleCellThree);
}
var elePreviousMessage = $(self.selectors.root, self.container);
if (elePreviousMessage.length > 0) {
btnClose = $(self.selectors.closeButton, elePreviousMessage);
btnClose.click();
setTimeout(function () { self.fadeIn(eleMessageBar, callback); }, self.globals.fadeDuration);
}
else
self.fadeIn(eleMessageBar, callback);
};
this.fadeIn = function (element, callback) {
element.prependTo(self.container).centerToScrollTop().fadeIn(self.globals.fadeDuration, function() {
if (callback != null)
if ($.isFunction(callback))
setTimeout(function () {
callback();
}, self.globals.callbackDuration);
});
};
self.initialize();
};
return publicInstances;
})(jQuery);
function initializeMessageBarManager() {
nalco.es.rk.globals.messageBarManager = new nalco.es.rk.source.MessageBarManager.Controller();
}
$(document).ready(function () {
initializeMessageBarManager();
if (typeof (Sys) != "undefined")
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(initializeMessageBarManager);
});
</script>
THIS IS THE EXTENSIONS DEPENDENCY LISTED IN THE FILES ABOVE:
// **********************
// .centerToScrollTop
// Use -
// Centers an ELEMENT to the window's scrollTop.
//
// Example -
// $('.myElement').centerToScrollTop();
// **********************
(function ($) {
$.fn.extend({
centerToScrollTop: function (options) {
return this.each(function () {
var element = $(this);
var container = $(window);
var scrollTop = container.scrollTop();
var buffer = 30;
var top = scrollTop + buffer;
var left = (container.width() - element.outerWidth()) / 2 + container.scrollLeft();
element.css({ 'position': 'absolute', 'top': top, 'left': left });
return element;
});
}
});
})(jQuery);
This type of error occurs usually if you forgot to include some files like jquery-ui.min.js etc. Check carefully if you add all the necessary references.