I want to make a dialog box where the user can see the image that he/she has just uploaded. The file uploading systems works fine but when I want to put the image into the dialog box dynamically only an empty box appears.
HTML Code:
<div id="dialogbox">{I want to change this conetent here to an image}</div>
jQuery/Javascript Code:
function completeHandler(event){
var data = event.target.responseText;
var datArray = data.split("|");
if(datArray[0] == "upload_complete_msg"){
hasImage = datArray[1];
$(function() {
$("#dialogbox").dialog();
$("#dialogbox").html('sadasdasd');
});
} else {
_("uploadDisplay_SP_msg_"+datArray[2]).innerHTML = datArray[0];
_("triggerBtn_SP_"+datArray[2]).style.display = "block";
}
The datArray[] is a response text from the PHP validation. datArray[0] is equal to upload_complete_msg if it succeeded, datArray[1] is the image file name and extension like filename123.jpg and darArray[2] is just an id. So as I said if the user has successfully uploaded the image a dialog box should appear. I tried to add more content with the .html() function but it didn't show me anything again just an empty dialog box. How would it be possible to put an image into this dialog box like $("#dialogbox").html('<img src="imgfolder/myimage.jpg">');?
Try something like this?
function completeHandler(event) {
var data = event.target.responseText;
var datArray = data.split("|");
if (datArray[0] == "upload_complete_msg") {
hasImage = "tempUploads/"+datArray[1];
// Create a jQuery image object, and assign the src attribute.
var imgEl = $("<img>").attr("src", hasImage);
// stick that imgEl into the dialog.
$("#dialogbox").html(imgEl);
$("#dialogbox").dialog();
} else {
_("uploadDisplay_SP_msg_" + datArray[2]).innerHTML = datArray[0];
_("triggerBtn_SP_" + datArray[2]).style.display = "block";
}
}
Related
hey there i'm making a simple webpage which requires to download an output image file at the last step..
but i don't know how can i add download button dynamically at correct time, because at starting of a page there is no need of download button..
so i have main.js file:
which looks something looks like this:
let img_code=document.getElementById('img_code');
let textbox=document.getElementById('textbox');
let gen_button_img=document.getElementById("img_button");
gen_button_qr.addEventListener("click",()=>
{
var trailer=textbox.value;
var url='www.example.com';
var result= url.concat(trailer);
if (navigator.onLine)
{
if(trailer.length<=1725 && trailer.length>0)
{
if((trailer !="0")&& (trailer.replace(/\s/g, '').length))
{
image_code.src=result;
alert("Image Generated successfully");
/**/
}
else
{
alert("You cannot create this file spaces only or only with single 0");
}
}
else
{
alert("Maximum charecter limit is exceeded!! ");
}
}
else
{
alert("No Internet Connection");
}
});
So, i have the question is there any way to dynamically add the button which takes file URL as input and download that file through web browser's downloader?
Note=>
I can easily save the result by right click on the picture and save image option; but i want to add an extra button to download the same file.
Most of the things explained in comments so read it first
// arrow function to create and append download button into any element
// it only takes url of file that will download.
const createBtn = (URL) => {
// create button element
const downloadBtn = document.createElement("button");
// you can set any name of id according to your choice
downloadBtn.setAttribute("id", "downloadBtn");
// create anchor element
const downloadLink = document.createElement("a");
// set any thing in inner text
downloadBtn.innerText = "Download Image";
// set download attribute to true
downloadLink.setAttribute("download", true);
// set url with URL
downloadLink.setAttribute("href", URL);
// append button element into anchor element
downloadLink.appendChild(downloadBtn);
// get that element in which download button will append
const container = document.getElementById("container");
// append download button into any element of your choice
container.appendChild(downloadLink);
};
// url of file
const URL = "https://images.pexels.com/photos/863963/pexels-photo-863963.jpeg?cs=srgb&dl=pexels-blaque-x-863963.jpg&fm=jpg"
// call createBtn function with URL
createBtn(URL);
<!-- The element in which download button will be appended -->
<div class="container" id="container"></div>
I am not 100% sure that this will work!
It also not work in stack snippet because iframe tag.
Try to use it locally.
I know that there are many questions and answers pertaining this, but i have tried but am still unable to do so. Please help.
Here is my js code:
$(document).ready(clicklistener); // once ready, run clicklistener function
function clicklistener() {
$(".image-thumbnail").click(popup); // run popup function when ".image-thumbnail" is clicked}
function popup() {
var srcname = $(this).attr("src"); // get source image filename
var newfile = srcname.replace("small", "large"); // replace with large img
if ($(this).parent().children("span").children("img").hasClass("image-popup")) { // traverse the elements to check if the image popup already exists
$(this).parent().children("span").remove(); // remove if it already exists
} else {
var printimg = "<span><img class=\"image-popup\"src=\"" + newfile + "\"></img></span>";
$(this).after(printimg); // create img if it doesn't exist
}}
Doesn't look like you have an event defined for closing it (unless you click on the popup). SO you need to write one:
$(document).ready(function(){
$(".image-thumbnail").click(function(){
// allow for body.click to first hide any current images
setTimeout(function(){popup($(this))}, 600)); // run popup function when ".image-thumbnail" is clicked
});
function popup($ele) {
var srcname = $ele.attr("src"); // get source image filename
var newfile = srcname.replace("small", "large"); // replace with large img
if ($ele.parent().children("span").children("img").hasClass("image-popup")) { // traverse the elements to check if the image popup already exists
$ele.parent().children("span").remove(); // remove if it already exists
} else {
var printimg = "<span><img class=\"image-popup\"src=\"" + newfile + "\"></img></span>";
$ele.after(printimg); // create img if it doesn't exist
}
}
$(window).click(function(){
$('.image-popup').remove()
});
})
I am trying to dynamically load data into the body of my modal but cannot seem to get it to work.
function legend(mb) {
var url = mb;
var location = document.getElementById("choice2");
var gwc = location.options[location.selectedIndex].value;
if (gwc == 15)
{
title = ['<strong>Geomorphology</strong>'];
var url = 'http://localhost/geoserver/apib/wms?REQUEST=GetLegendGraphic&VERSION=1.1.0&FORMAT=image/png&WIDTH=20&HEIGHT=25&LAYER=apib:chamapwathi_block_gm&legend_options=fontSize:14';
}
}
Considering you have only the javascript tag there, I am adding a basic javascript solution. In my example, content changes on button click, which you would have to do when you get the data from your API call.
I have also added an id attribute to the modal body.
document.getElementById('left-modal-body').innerHTML = 'Hello';
Updated Example
How is it possible to upload a file directly without clicking file upload button(I want to click Add Widget Button which should give file upload dialog box)
I have a button declared as follows:
<button class="add-button" style="float:top;">Add Widget</button>
On clicking the button the following function is invoked
$(".add-button").on("click", function() {
// get selected color value
var color = $color_picker.val();
// build the widget, including a class for the selected color value
var $widget = $('<li>', {
'class': 'color_' + color
})
.append($('<button>', {
'class': 'delete-button',
'text':'-'
}))
.append($('<img src="abc.png" height="60px" width="60px">'));
// add widget to the grid
gridster.add_widget($widget, 1, 1);
});
But I first want a upload box to appear where in user can upload the image as soon as the button is clicked then the above code should get executed
I did something like this
$(".add-button").on("click", function() {
var x = document.createElement("INPUT");
x.setAttribute("type", "file");
x.setAttribute("onclick","previewFile()");
// get selected color value
var color = $color_picker.val();
// build the widget, including a class for the selected color value
var $widget = $('<li>', {
'class': 'color_' + color
})
.append($('<button>', {
'class': 'delete-button',
'text':'-'
}))
.append($('<img src="abc.png" height="60px" width="60px">'));
// add widget to the grid
gridster.add_widget($widget, 1, 1);
});
But this does not brings any dialog box where user can upload the image
This uploaded image I want to then use in the place of
.append($('uploaded image'));
Preview File Function (This also needs to be modified)
function previewFile() {
var preview = document.createElement('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader(); //API for reading file stored on user computer
reader.addEventListener("load", function () { //"load" :This eventlisterner "listens" loading of file. Once it is loaded function is triggered
preview.src = reader.result;
});
if (file) {
reader.readAsDataURL(file); // helps in reading the content of "file"
}
document.body.appendChild(preview);
}
My aim is that preview file function should return an image which I can put in
.append($('image from preview file'));
A version of code is at Fiddle
The way to do this is to have some hidden input with file type somewhere on the dom. You might be able to programatically put it there, but really no point in that. Once the add widget button is clicked, you can simulate a click for the hidden input. This will initiate a prompt to pick a file. Then what you want to do is, wait until the file has been "picked" by the user. This is done via the onchange event. Within that, you can grab the file, read it, and then when it's done you can have a callback via the onload method. I put up a working example here. I imagine you wanted to have the file picked as the image set on the src, so I did that as well.
hidden input
<input id="test" type="file" style="position: absolute; top: -10; left: -10; height: 0; width: 0;" />
button click function (this is what will wait until the file has been chosen), the call back method is used on the onload event of the filereader.
$(".add-button").on("click", function() {
$('#test').click();
$('#test').on('change', function(e) {
var test = document.getElementById('test');
if (!test) {
alert("Um, couldn't find the fileinput element.");
}
else if (!test.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!test.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
file = test.files[0];
console.log(file);
fr = new FileReader();
fr.readAsDataURL(file);
fr.onload = function() {
var data = fr.result; // data <-- in this var you have the file data in Base64 format
callbackAddButton(data);
test.value = ''; //here we are resetting the file input's files
$('#test').replaceWith($('#test').clone()); //here we are resetting the input, if we clone the input with the files then it wont trigger the onchange event if you upload same image. So we need to make sure we have these 2 calls.
};
}
})
});
And finally, the callback method. Which is simply exactly what you had before but now only gets called once the file has been done (done as in, you read it via filereader and have access to contents if needed). The only difference here is now you have a base64 representation of the image the user uploaded. Which I am setting to the new image widget you created.
function callbackAddButton(file) {
// get selected color value
var color = $color_picker.val();
// build the widget, including a class for the selected color value
var $widget = $('<li>', {
'class': 'color_' + color
})
.append($('<button>', {
'class': 'delete-button',
'text':'-'
}))
.append($(`<img src="${file}" height="60px" width="60px">`));
// add widget to the grid
gridster.add_widget($widget, 1, 1);
}
EDIT
Once you're done with the input file element, it's good practice to now clear it because you dont need the file anymore (from the input at least, since you have a base64 representation). Just append a $('#test').replaceWith($('#test').clone()) after the you make the callback call.
I've created a custom ribbon button where i load external content into a Modal Dialog. I want to insert some text on the editor and close the dialog. The function OnPopClosed is running when I click something on my dialog but I'm having an error: RTE is not defined, so I can't insert anything on the editor. Any ideas?
function init(){
var options = SP.UI.$create_DialogOptions();
options.title = "Sharepoint Plugin";
options.width = 600;
options.height = 400;
options.url = '/_Layouts/Test/Test.aspx';
options.dialogReturnValueCallback = OnPopClosed;
SP.UI.ModalDialog.showModalDialog(options);
}
function OnPopClosed(test) {
var range = RTE.Cursor.get_range();
range.deleteContent();
var selection = range.parentElement();
if (!selection) {
return;
}
range.insertNode(elem);
RTE.Cursor.get_range().moveToNode("test");
RTE.Cursor.update();
SP.UI.ModalDialog.commonModalDialogClose(1, "test");
}
Place RTE actions in SP.SOD.executeOrDelayUntilScriptLoaded in order to execute the specified function if the file containing it is loaded (in your case sp.ui.rte.js):
ExecuteOrDelayUntilScriptLoaded(RTEActions, "sp.ui.rte.js");
Example:
function RTEActions()
{
var range = RTE.Cursor.get_range();
//Remaining code goes here...
SP.UI.ModalDialog.commonModalDialogClose(1, "test");
}
then declare the dialog handler like this:
function OnPopClosed() {
ExecuteOrDelayUntilScriptLoaded(RTEActions, "sp.ui.rte.js");
}