How to load images from a directory using jquery - javascript

I am toying with the following code trying to take images from a set directory, and preload them. I do not want to load the images into a div, but rather preload them in the memory using the normal:
new Image().src = "/wp-content/themes/NCHERM_Theme/images/home4-events.jpg";
I am rather new to jquery so looking for some help to finalize this:
window.onload = function($) {
var folder = "images/preload";
$.ajax({
url : folder,
success: function (data) {
//go through each item in folder
$.each(data, function(i,filename) {
//take each item and run into the normal preload method
setTimeout(function() {
// preload images
new Image().src = filename;
}, 1000);
});
}
});
};
running this in wordpress I get `403 forbbiden' on the url for the folder before i can even test if this is working

Make sure you have added reference of JQuery inside your <script> tag. JQuery Library is missing.
<script src="../../jquery.min.js" type="text/javascript"></script>
For your reference: $.ajax is not a function

Try this code if it work for you.
window.onload = function($) {
var folder = "images/preload";
$.ajax({
url : folder,
success: function (data) {
//go through each item in folder
$.each(data, function(i,filename) {
//take each item and run into the normal preload method
setTimeout(function() {
// preload images
var $img=$("<img />",{"src":filename});
$('#target_id').append($img);
}, 1000);
});
}
});
};

You can solve 403 error by adding:
Options +Indexes
On .htaccess file.

Related

How to reinitialize a dropzone element

I want to use dropzone to display thumbnails of images that I already have on the server. I am creating a CMS for a property website. The server has images associated with Sites of properties. When the page loads, the init function of my dropzone displays the relevant image for a given site as a thumbnail in the dropzone.
There is a drop down box on the page which lets the user select another site. When they do this I want the dropbox object to basically do what's in the init function again. Make a call to the server and display the thumbnails that are associated with this different site.
I haven't been able to get a solution yet (obviously). Typically I will get something like, "dropzone still attached" with stuff I have tried. I can't seem to see anything in the docs that is useful.
Any help would be appreciated :)
//my dropzone object
var myDropzone = $('#featured-development-dropzone').dropzone({
url: '#Url.Action("SaveFeaturedDevelopmentImage","Homepage")',
maxFiles: 1,
addRemoveLinks: true,
init: function () {
var myDropzone = this;
$("select").on('click', function () {
myDropzone.removeAllFiles(true);
});
var siteID = $('#siteDropdown').find(':selected').val();
$.ajax({
url: '#Url.Action("GetFeaturedDevelopmentImage", "Homepage")',
data: { siteID: siteID },
type: 'GET',
success: function (data) {
console.log(data);
if (data.data != null) {
var mockFile = {
name: data.filename,
size: data.fileSize
};
// Call the default addedfile event handler
myDropzone.emit("addedfile", mockFile);
console.log(typeof (data));
// And optionally show the thumbnail of the file:
myDropzone.emit("thumbnail", mockFile, "data:image/png;base64," + _arrayBufferToBase64(data.data));
myDropzone.emit("complete", mockFile);
}
}
});
this.on("sending", function (file, xhr, formData) {
formData.append("SiteID", siteID);
formData.append("imageTypeID", 4);
console.log(formData);
});
}
});
var prevSiteID;
$("select").on('click', function () {
prevSiteID = this.value;
}).change(function () {
var newSIteID = this.value;
// potentially put code here that will reinitialize the dropbox and display images associated with different site.
console.log(prevSiteID);
console.log(newSIteID);
changeFeaturedDevelopment(prevSiteID, newSIteID);
I belive you need to recall that function again. Since when you are triying to attach a new image, the dropzone zone is already defined in the page load. Or you call the init again or try to reset it, so the dropzone can reattach another image.

How can I apply a watermark in images using JavaScript?

I'm using angularJS and need to apply a watermark programatelly in images by calling an JS function. What I have is:
<figure><img class="watermark" ng-src="{{applyWatermark(img.url)}}"></figure>
So, I need to call that function applyWatermark (not implemented yet) and return a img with the watermark, but I'm not sure how can I build this function. Should it return the image? Can someone provide me some example how can I do this?
EDIT:
I did this, but it's not working:
$(function applyWatermark(image) {
watermark([image, 'watermark.png'])
.image(watermark.image.lowerRight())
.then(function (img) {
return img
});
})
Any idea?
Using watermark.js:
watermark(['/img/forest.jpg', '/img/logo.png'])
.image(watermark.image.lowerRight(0.5)) // Or lowerRight() for no opacity
.then(function (img) {
document.getElementById('alpha-image').appendChild(img);
});
If this doesn't work for you, maybe try this:
$.ajax({
url: 'http://www.example.com/your-image.jpg',
type: 'HEAD',
error: function() {
// File isn't found
},
success: function() {
// File is found! Do the watermarkage.
}
});
to test if the image exists before processing.

jQuery: Uncaught Error: Syntax error, unrecognized expression: (bunch of photo caption text data)

I am attempting to add text from a jQuery array at a given point to my webpage. The page is set up so that when I click on a thumbnail, a larger image and caption data are to show on the page, however the caption text is not showing. $(caption[this.id]).text().appendTo('#images'); is where the error comes from, though if I do a simple DOM.write with the (caption[this.id]).text(), the words will show on the page.
// App variables
var filename = [];
var caption = [];
var id = [];
var counter = 0;
var thumbs = $([]);
var images = $([]);
//Make an AJAX call to load the XML file data
$.ajax({
url: 'gallery.xml',
dataType: 'xml',
success: function (data) {
$(data).find('gallery').each(function () {
// Gather the image filenames
$(data).find('image filename').each(function () {
counter++;
id.push(counter);
filename.push($(this).text());
});
//console.log(filename);
// Gather the image captions
$(data).find('image caption').each(function () {
caption.push($(this).text());
});
});
// Run the thumbnail loading procedure when the AJAX call has completed
loadThumbs();
loadImages();
},
error: function () {
// Failure alert if XML was not loaded
alert("XML file couldn't load...");
}
});
// Loop through filename list and create large image for each entry
var loadImages = function() {
$.each(filename, function (_, src) {
images = images.add(
$('<img />', {src: 'images/' + src, class: 'largeImage', height: '100px', width: '100px'})
);
});
// Add first image to default
$(images[0]).appendTo('#images')
};
// Do some shit when image is clicked...
$( document ).on( "click", "img", function() {
// Empty viewing DIV and create a new large-scale version of the image for viewing
$('#images').empty();
$(images[this.id]).appendTo('#images');
//THIS IS WHERE ERROR COMES FROM
// Add text to <span> to solve error?
$(caption[this.id]).text().appendTo('#images');
});
The error is specifically:
I can add all of the JS code if there is not enough here to understand. Thanks in advance.
You're passing the caption text to jQuery:
$(caption[this.id])
The library is trying to parse it as a CSS selector, and it can't so it throws the error.
You could do several things to make it work, and your suggestion in the comment is a good one:
$("<span/>", { text: caption[this.id] }).appendTo("#images");

Get text file contents using JQuery in an external file

I have an external javascript file that I want to use to collect the contents of a number of text files. JQuery .get() seems the most obvious choice. I can make this work if the JQuery is in the page, but not when the JQuery is in the external file. I'm missing something hugely simple...and I am currently mixing normal javascript with JQuery in the same file which I fear is poor form.
All files I am trying to access are within the same file structure. Currently I have the following in my external .js:
function addPanels() {
// eventually loop over list of local HTML files
// and do some stuff with the results...
fileContents = readHTMLFile();
}
jQuery(function($){
readHTMLFile = $.get('../html/test.html', function(data) {
alert('Loaded something');
return(data);
});
});
My HTML page contains the following:
<script type="text/javascript">
$(document).ready(function(){
addPanels();
});
</script>
Pretty sure this is a RTFM moment so direction towards the right manual/tutorial would be great!
Dan
The jQuery.get is a asynchronous function, with a callback that executes when the server returns the requested document. Therefore, you cannot return any data from the method.
function addPanels() {
// will not work
fileContents = readHTMLFile();
}
...
readHTMLFile = $.get('../html/test.html', function(data) {
// will not work
return(data);
});
This however, will work:
var addPanelCallback = function(html) {
// append html (or something like that)
alert(html);
};
var addPanel = function(url) {
$.get(url, addPanelCallback);
};
addPanel('../html/test1.html');
addPanel('../html/test2.html');
Example: http://jsfiddle.net/FgyHp/
In your script "readHTMLFile" is not known by function "addPanels", you should put them in same level.
This script should works
<script type="text/javascript">
(function($){
var readHTMLFile = function(url){
var toReturn;
$.ajax({
url: url,
async: false
}).done(function(data){
toReturn = data;
});
return toReturn;
};
$.addPanels = function(url){
fileContents = readHTMLFile(url);
};
})(jQuery);
</script>
And in your page you can call it like that:
<script type="text/javascript">
$(document).ready(function(){
$.addPanels('../test/test.html');
});
</script>

Organize JS code in MVC app

I have several JS code in several partials Views.
I think it would be good idea to put all these code in separated JS file to separate JS code from HTML code.
But how do you deal with MVC code inside JS?
The example below is JS code which I have in partial View. I would like to put in into JS file but the JS code has MVC code #Url.Action("ResultForm", "File") and it will not be executed in JS file.
Any suggestion?
Javascript Code
<script type="text/javascript">
var varTimerSpeed = 5000;
var varTimerInterval;
var onlyOneInstance = false;
startTimer();
function startTimer() {
onlyOneInstance = false;
varTimerInterval = setInterval(loadResultForm, varTimerSpeed);
}
function loadResultForm() {
if (onlyOneInstance) return;
clearInterval(varTimerInterval);
onlyOneInstance = true;
$.ajax({
url: '#Url.Action("ResultForm", "File")',
data: '',
dataType: 'html',
success: function (data) {
$('#ResultForm').html(data);
startTimer();
}
});
};
</script>
I am assuming using a Razor partial for only the js code is not an option. In that case you could use this approach:
in your view.cshtml
<script type="text/javascript">
var Namespace.urlForModule = '#Url.Action("ResultForm", "File")';
</script>
<script type="text/javascript" src="customScript.js"></script>
in you customScript.js
$.ajax({
url: Namespace.urlForModule,
})
The idea is to separate out the Asp.Net MVC specific code from the js code.
The way you want to do that is upto you. As some one else suggested, you could attach data-* attributes to some div and read those. I prefer this, as it expresses my intent clearly.
A solution would be to create a meta tag or a data-* attribute with the desired dynamic value and catch it with JavaScript. This way you can separate the code entirely with minor changes.
You can add hidden field with url:
// View:
#Html.Hidden("LoadResultFormUrl", #Url.Action("ResultForm", "File"))
// js-file
function loadResultForm() {
url = $("#LoadResultFormUrl").val();
...
};
why dont you just create a partial view which contains nothing but js code
and do a renderpartial instead of adding a script tag?
Create a file "somescript.js" and put the code inside a unique public function, extract hard-coded external dependencies and replace them for parameters.
var startXyz = function(resultFormUrl) {
var varTimerSpeed = 5000;
var varTimerInterval;
var onlyOneInstance = false;
startTimer();
function startTimer() {
onlyOneInstance = false;
varTimerInterval = setInterval(loadResultForm, varTimerSpeed);
}
function loadResultForm() {
if (onlyOneInstance) return;
clearInterval(varTimerInterval);
onlyOneInstance = true;
$.ajax({
url: resultFromUrl,
data: '',
dataType: 'html',
success: function (data) {
$('#ResultForm').html(data);
startTimer();
}
});
};
};
Then, in your page you do:
<script>
$(function(){
startXyz('#Url.Action("ResultForm", "File")');
});
</script>
Now you have a modular function that will startup your page/partial and a script file that do not depends directly from server state and can be reused on the same or another page.
This approach is especially useful if a partial view is rendered more than once per page.

Categories