I've this in my html file
<div class="change">
<div id="changed" onclick="change_DImage()">New Upload...</div>
<input id="browse" type="file" onchange="ImagLoc()">
</div>
and this in javascript file
function change_DImage(){
document.getElementById("browse").click();
}
function ImagLoc(){
var x = (document.getElementById("browse").value).toString();
var ImgId = x.substr(12,6);
var NewImg = "url('./image/MyAlbum/" + ImgId + "')";
document.getElementById("dailyPic").style.backgroundImage = NewImg;
}
it's work pretty well but when I refresh my browser it'll change back to the default
for this in css file
background-image: url("../image/smokebird.jpg");
On page reload obviously image is going to reset to the original image. To keep it as it is even after page refresh you can do,
Save the image in Cookie (base 64 format), but there is a size limit since you can save small size images only.
On image select, you can save the image file remotely on your server asynchronously (using AJAX) and you can recall the image using the server session.
Javascript manipulates the only current state of the Html, not the file on server side. To handle it, you have to store state on server side, and change it both client and server side on button click.
Storing changed value on browser's cookie or local storage, and get stored one on page load is another option.
localStorage example:jsfiddle
However localStorage can be easily cleaned by user, even by mistake. I have found this answer useful about how it can be cleaned: SO link. Other drawback (if your really care about it) is a need of use Inline styling. There is attr css function but other than content usage is currently limited so I would stick to Inline styling.
I made more understandable version including your code, here:
jsfiddle, however I am not sure what this line and function suppose to do so I have removed it:
<div id="changed" onclick="change_DImage()">New Upload...</div>
Edit:
obviously second jsfiddle code will not work on jsfiddle, you need to inject it to your code.
Related
Im using this code, it only affects the file (my settings.html file) where i change the value of the background color:
function background() {
`var x = document.getElementById('color').value;
document.body.style.backgroundColor = x;
}
color is the id of the input.
But how can i affect multiple html files with this?
Every time you navigate to another page, your HTML and JS script will be refreshed, and therefore you will lose your changes.
A possible solution is to use a cookie or the browser's localStorage in order to save the value of the desired color. Then, it can be reused when navigating pages.
Example of setting a cookie using JS:
https://www.w3schools.com/js/js_cookies.asp
Example for localStorage:
https://www.w3schools.com/jsref/prop_win_localstorage.asp
Hope this helps!
You can import the JavaScript file into multiple HTML files:
<script src="filename.js">
Then run the function in said HTML Files.
Also make sure there is one "color" Id in each HTML File.
I am new to HTML5 and javascript and I have a question.
I have the following HTML code
<img id='image_preview'/>";
<input type='file' name='fileUpl' id='fileUpl' onchange='doUpl();' accept='image/*'/>
So in short, there is a button, every time I click it, doUpl() is executed. It loads a picture and shows a preview of the picture into <img ... >
the js function is
function doUpl() {
var file = document.getElementById('fileUpl').files[0];
...
dataUrl = canvas.toDataURL("image/jpeg");
document.getElementById('image_preview').src = dataUrl;
...
I would like to have the input field pre-loaded with a default picture path (ex. c:\test.jpg) and the preview of test.jpg already shown when the page is loaded the first time. If the button is pressed the picture is updated.
At the moment, when I first load the html page there is no preview and the input path is empty.
Can anyone help me with this?
Thanks :)
edit: sorry for the confusion. the test img is of course on the server not on the client PC.
I would like to have the input field pre-loaded with a default picture path (ex. c:\test.jpg)
You can do that using the value attribute. Something like this:
<input type='file' name='fileUpl' id='fileUpl' onchange='doUpl();' accept='image/*' value='c:\test.jpg'/>
the preview of test.jpg already shown when the page is loaded the first time.
There are a couple ways you can do this. The basic one is to do like above, using the src attribute:
<img id='image_preview' src='c:\test.jpg'/>"
But, I think is better to do using javascript, because, if one day you need to change this standard image, you only change it on the input element.
</body>
<script>
// self executing function here
(function() {
doUpl(); //this will execute when page is loaded.
})();
</script>
P.S. This is only possible if you have c:\test.jpg on your server
You can check if there is something on the input and fake the img and fake the path but you cannot get a real image from the user hard drive because it's security
If you are talking about preloading images from the client's filesystem, I'm afraid this is not possible due to obvious security reasons:
The specification of the File API states that:
(..) This specification also assumes that the primary user interaction is
with the element of HTML forms [HTML], and that
all files that are being read by FileReader objects have first been
selected by the user (..)
in index.html background is changing randomly when you open it
var imgArr=['background.jpg', 'backgrounds2.jpg', 'backgrounds3.jpg'];
i=Math.round(Math.random()*2);
$('.wrap').css({'background': 'url('+imgArr[i]+') no-repeat fixed'});
in other pages i don't need to change background but use one from index.html
how can i save one var value from index.html and use it in other pages without changing?
You can use cookies or localStorage or even better sessionStorage.
var imgArr=['background.jpg', 'backgrounds2.jpg', 'backgrounds3.jpg'];
i = Math.floor(Math.random() * imgArr.length);
//fewer harcoded values is better :-)
$('.wrap').css({'background': 'url('+imgArr[i]+') no-repeat fixed'});
sessionStorage.setItem("bg", imgArr[i]);
Of course you should check if storage is available before attempting to access it, but it will be available in modern browsers.
The easiest way would be to jsut set a default in the CSS - your JS would then override that on index.html, and if you omit the js from the other pages then it will revert to the default.
You could also use JS to set a cookie and then read from that but then youd still need to plan for if someone accesses page without having the cookie set, so id probably go with the CSS option were I you.
If you are using any server side language then try SESSION to store the value.
If you are using only client-side language then try using cookie or pass the value through parameter to the next page.
You can add some element to index.html and check in your javascript if it exists it will mean that you are on index.html page and you should change background. For example add
<div id="iamindex"></div>
And you javascript:
if($('#iamindex').length) {
var imgArr=['background.jpg', 'backgrounds2.jpg', 'backgrounds3.jpg'];
i=Math.round(Math.random()*2);
$('.wrap').css({'background': 'url('+imgArr[i]+') no-repeat fixed'});
}
I am working on a website:
http://tawfiq-aliyah.co.uk/epic/Site2/
I want the user to be able to set the BackgroundImage. I have implemented this with the pop-up menu in the bottom left hand corner already. But what I want is for the data about the users choice of background image to be stored so that when they come back to the site or move to another page on the site it loads the same background image.
I have looked into java cookies on the w3schools.com website
w3schools.com/js/js_cookies.asp
I have looked at the example but I am not sure how to get the cookie to store the backgroundImage of the instead of storing a username.
Any help would be much appreciated.
Thanks
In the click handlers for the thumbnails in the background image selector you do things like this:
onclick="main.style.backgroundImage='url(images/back3.jpg)'"
If you replace that with a function:
onclick="setBackgroundImage('images/back3.jpg')"
and then
function setBackgroundImage(url) {
main.style.backgroundImage = 'url(' + url + ')';
setCookie('BG', url, 100); // Or however many days you want.
}
And then, in an onload handler, do something like this:
var bg = getCookie('BG');
if(bg)
main.style.backgroundImage = 'url(' + bg + ')';
You might want to do more sanity checking on the cookie value though, you have a list of available backgrounds kicking around so you could just check that bg is defined and that it is in the list.
Also, you might want to use absolute URLs for your images rather than relative ones, that makes it easier to move things around.
I've never worked with cookies in javascript, but looking at the w3c exampple you provided, wouldn'nt it be fine to use that technique and just store the url instead of the username? And then set the img:src or background-url or what ever you are using to that url from the getCookie function? (or later, whenever the dom is ready).
An alternative could be to use local storage, but it might be overkill for what you are trying to do.
Javascript can manipulate the document the browser is displaying, so the following:
<script>
document.write("<table><tr><td>Hola</td><td>Adios</td></tr></table>");
</script>
Will make the browser display a table just like if it was the original HTML document:
<table>
<tr>
<td>Hola</td>
<td>Adios</td>
</tr>
</table>
Is there a way I can save/serve this document content?
Currently we have some nicely generated reports using Ext-js, what I would like to do is to have the "text/html" version of it ( I mean, something that doesn't require javascript )
So at the end of the page I would add a button : "Save as blaba" and the document should display the text/plain version.
The only way I could think right now is, to write the content into a javascript variable like:
var content = document.toString(); // or something magic like that.
// post it to the server
Then post that value to the server, and have the server present that value.
<%=request.getParameter("content-text")%>
But looks very tricky.
Is there an alternative?
EDIT
Ok, I almost got it. Now I just need the new window to pop up so the option "would you like to save it shows"
This is what I've got so far
<script>
document.write("<div id='content'><table><tr><td>Hola</td><td>Adios</td></tr></table></div>");
function saveAs(){
var sMarkup = document.getElementById('content').innerHTML;
var oNewDoc = document.open('application/vnd.ms-excel');
oNewDoc.write( sMarkup + "<hr>" );
oNewDoc.close();
}
</script>
<input type="button" value="Save as" onClick="saveAs()"/>
The line:
var oNewDoc = document.open('application/vnd.ms-excel');
Should specify the new content type, but it is being ignored.
Unless its being saved client side with File -> Save Page As..., you will have to do exactly what you are proposing, posting $('body').html() to your server and process it as text.
Here's the upgraded version to open the table contents in .xls format.
<head>
<script>
document.write("<table id='targetTable'><tr><td>Hola</td><td>Adios</td></tr><tr><td>eins</td><td>zwei</td></table>");
function saveAsXLS()
{
var xlObj = new ActiveXObject("Excel.Application");
var xlBook = xlObj.Workbooks.Add();
var xlSheet = xlBook.Worksheets(1);
for (var y=0;y<targetTable.rows.length;y++) // targetTable=id of the table
{
for (var x=0;x<targetTable.rows(y).cells.length;x++)
{
xlSheet.Cells(y+1,x+1)=targetTable.rows(y).cells(x).innerText;
}
}
xlObj.Visible=true;
document.write("The table contents are opened in a new Excel sheet.");//Print on webpage
}
</script>
</head>
<body>
<input type="button" value="Open table in Excel!" onclick="saveAsXLS()"/>
</body>
This code is tested in IE6 and is using ActiveXObject control.
The table I've used here is of order 2x2 and the individual contents are mapped respectively into the excel sheet.
Unlike the .doc version, this does not save the file in client's system. It opens the application with the table content and the client has to save it.
Hope this helps in answering ur question. Lemme know if u face any issues.
Peace.
Depending on your browser support requirements, you could use data URIs
Core for proof of concept (tested in Firefox 3.5.3):
document.write("<div id='content'><table><tr><td>Hola</td><td>Adios</td></tr></table></div>");
function extract(){
return document.getElementById('content').innerHTML;
}
function dataURI(s){
return 'data:application/vnd.ms-excel;base64,' + encode64(s);
}
document.write('open');
I pulled base 64 encode/decode from examples online. Careful: the one I grabbed included a URI encode before base 64 encode that messed me up for a while.
You are getting close to the answer I thinks. The problem is that 'document.open(...)' can only take standard mime-types such as 'text/html', 'text/plain' and a few others
And because of that your code should be:
<script>
document.write("<div id='content'><table><tr><td>Hola</td><td>Adios</td></tr></table></div>");
function saveAs(){
var sMarkup = document.getElementById('content').innerHTML;
var oNewDoc = document.open('text/html');
oNewDoc.write( sMarkup + "<hr>" );
oNewDoc.close();
}
</script>
<input type="button" value="Save as" onClick="saveAs()"/>
Hope this helps.
$(function(){
$('.bbutton').click(function(){
var url='data:application/vnd.ms-excel,' + encodeURIComponent($('#tableWrap').html() )
location.href=url
return false
})
})
.table{background:#ddd;border:1px solid #aaa;}
.table thead th{border-bottom:1px solid #bbb;}
.table tr td{background:#eee;border-bottom:1px solid #fff;
border-left:1px solid #ddd;text-align:center;}
.table tr:hover td{background:#fff;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='tableWrap'><table style='width:98%;box-shadow:none;' class='table'>
<thead><th>id</th><th>Name</th><th>Address</th></thead>
<tr><td>1</td><td>Jyoti Telecom Services</td><td>http://www.tsjyoti.com</td></tr>
<tr><td>2</td><td>Recharge</td><td>http://recharge.tsjyoti.com</td></tr>
<tr><td>3</td><td>Bhuri Bharaj</td><td>http://bhuribharaj.tsjyoti.com</td></tr>
</table></div>
<p>Your download's ready as Excel Sheet <a href='#'class='bbutton'>Click Here for download</a></p>
If it's just a report, you could use server-side JavaScript to generate it, and then serve it up with whatever MIME type you need...
I dont think that sending your html to the server is a tricky solution. You just have to remember to give a link to your user to download this file. This can be done using a traditional POST, or even using AJAX. It depends on how you want your users to interact if your page.
Using traditional post, you could put all the html content in the value attribute of an input type hidden in your page, named "html_content" or something like that, and when the user clicks in the button "save" you send your user to another page with a link do the file. You send the html to server, a script creates a file in a filesystem with an unique name, and returns a download link.
Using AJAX, you just need to do an AJAX POST passing this variable, and then your script returns a download link, and you dynamically put it in your html - without reloading your page, like it was "only cliente side".
Either way, you'll return a link to the resource you just created in your filesystem with a html extension. Remember to generate unique names in your server for each generated file to avoid collisions.
Beware though that using innerHTML in IE 6 (I dont know if this is a IE family behavior or just about the 6 version) uppercases all tags and removes quotes from attributes. If you're planning to do some post processing in your html, be careful.
I dont know how jQuery or other JS libraries behaves in such situations. I would suggest using it though, they have plenty of browser compatibility checks to abstract all these hacks we use.
Here's my code to save the generated content[client-side] by the JavaScript to the local C: drive in MSWord[.doc] format.
<script>
document.write("<div id='content'><table><tr><td>Holaa</td><td>Adiosa</td></tr></table></div>");
function saveAs()
{
var wordObj=new ActiveXObject("Word.Application");
var docText;
var obj;
var textToWrite = document.getElementById('content').innerHTML;
if (wordObj != null)
{
wordObj.Visible = false;
wordDoc=wordObj.Documents.Add();
wordObj.Selection.TypeText(textToWrite);
wordDoc.SaveAs("C:\\Eureka.doc");
wordObj.Quit();
document.write("The content has been written to 'C:\\Eureka.doc'");//Print on webpage
}
}
</script>
<body>
<input type="button" value="Save in C:" onclick="saveAs()"/>
</body>
I quickly worked on ur issue and came up with this piece of code. Hope I understood your issue correctly.
The contraints in my code are
File format is .doc and not .xls.
Secondly, The file is saved in a static location and not the user specified location[can be optimized].
And, the code uses ActiveX and I didnot check the working in server-side environment.
These need to be addressed in the upcoming versions. (:
Peace.
Is your javascript AJAX which fetches the document.writeln() content from the server, or are you already generating that content when the page is served to the user ? Because if it's the former, I see no reason why you can't save any variables / queries in the session of whatever server-side technology your using and then just generate the plain text stuff from those. Otherwise, you'll have to folow voyager's suggestion above.
Since you're using Ext JS, you probably have a Store object that provides data to the grid? You should be able to extract the data you need by walking through the Store, and then format it the way you want. I don't think scraping the data from the generated HTML is ideal.
Once you grab the data you need from the grid and format it into text, you could POST it to the backend to initiate a download (with Content-Disposition: attachment etc.)
If you're not concerned with being cross-browser, you can also use the data: URL scheme to initiate a download without involving the backend.
This plugin does the job. Tested on IE, FF & Chrome.
https://github.com/dcneiner/Downloadify