Have a template with button..
Onclick of the button loading another template using Jquery load().
Example:
Template1:
<div id='tp1'>
<button>Load</button>
<div class="sub"></div>
</div>
Template2:
<div id='tp2'>
<img src='../abc/amd/aa.jpg' class="iPath"/>
<img src='../edf/dfv/bb.jpg' class="iPath"/>
<img src='../fgh/vbf/cc.jpg' class="iPath"/>
</div>
Now I need to change the src of tp2 for all the images, but the paths for each image is different.
img1 path: ../qwe/afg/aa.jpg
img2 path: ../asd/zvb/bb.jpg
img3 path: ../zxc/qrt/cc.jpg
Jquery:
$(document).ready(function(){
$('button').click(function(){
$('.sub').load("../abbb.html");
console.log($('.iPath'));
});
});
But here the iPath is undefined, because the load of the template 2 is not rendered.
How do I know whether the page is successfully loaded or not, so that it will be easy to change the source of the page....
Try adding a callback to load(), with required data.
A callback function that is executed when the request completes.
$('.sub').load("../abbb.html",function(data){
$(data).find('.iPath');
});
To change the src of image, you need to set the attribute using
$('.sub').load("../abbb.html",function(data){
$(data).find('.iPath').each(function(){
$(this).attr('src','...')
});
});
Try Like
$('img').each(function () {
var src = $(this).attr('src');
$(this).attr('src', 'newsrc');
});
OR
$("#ID > img").each(function() {
var src = $(this).attr('src');
$(this).attr('src', 'newsrc');
});
Load Using
$(function()
{
$("#div").load("page.html", function(responseText, statusText, xhr)
{
if(statusText == "success")
alert("Successfully loaded the content!");
if(statusText == "error")
alert("An error occurred: " + xhr.status + " - " + xhr.statusText);
});
});
Related
This is the code I'm using to get all loaded images:
$("img").on('load', function() {
console.log('Image Loaded');
}).each(function() {
if(this.complete){
//$(this).trigger('load');
var img = $(this).attr('src');
console.log(img);
}
});
but it's not working with those that are loaded with ajax afterwards, so I tried:
$(document).on('load', 'img', function(){
console.log('Image Loaded');
}).each(function() {
if(this.complete){
//$(this).trigger('load');
var img = $(this).attr('src');
console.log(img);
}
});
but it's not doing anything, what would be the correct way? I need to manipulate the parent divs of each image that is freshly loaded, so getting just all images period on every ajax load would be overkill and not elegant
How about this?
$(document).on('load', 'img', function(){
console.log('Image Loaded');
var parent = $(this).parent(); //or .parents('div') or .closest('div'), etc..
//do something with parent
});
I will suggest that you create a function for getting images and also call the same function after ajax execution.
Edit
Pass an id or class string present in document or returned ajax data to limit the scope of the function
function getImages(id) {
$('#' + id).find("img").on('load', function() {
console.log('Image Loaded');
}).each(function() {
if(this.complete) {
//$(this).trigger('load');
var img = $(this).attr('src');
console.log(img);
}
});
}
getImages('outsideAjax'); // call during normal execution. outsideAjax is an id within your html document but not in the returned ajax data
$.ajax({
// ajax settings
}).done(function() {
// post ajax code
// append returned data to document
getImages('insideAjax'); // recall after successful ajax execution and appending of returned data. 'insideAjax' is an id inside your return ajax data
}).fail(function(jqXHR, textStatus, errorThrown) {
// report error
});
This is how I solved it:
<img src="' + picUrl + '" onload="checkPic(\'' + picUrl + '\', this.naturalHeight, this.height);" class="pic">
Inside AJAX response.
I think it's self explanatory, works perfectly!
In the checkPic functuion I find this element by the src and get the parent elements and so on.
This is an ASP.Net MVC 5 project.
I have a simple javascript/jQuery as follow:
<script>
$(document).ready(function () {
$("#textBox").focusout(function () {
var phrase= $("#textBox").val();
phrase= phrase.replace(new RegExp(/\s+/, 'g'), "%20");
$("#commentDiv").load("../Search/SearchSingular?phrase=" + phrase);
});
});
</script>
As you can see, there is a jQuery .load method which calls SearchSingular action in the Search controller when the focus is out from HTML element with id = textBox. This works well, except that the SearchSingular action execution may sometimes take time to finish.
Thus, I want to show a loading image when the load is not finished. Is there any way to do this?
Turn it into a callback
// Somecode to display a image
$("#commentDiv").load("../Search/SearchSingular?phrase=" + phrase, function() {
// Somecode to remove image
});
You can use a loading image while div contents load
("#loadingImage").show();
$("#commentDiv").load("../Search/SearchSingular?phrase=" + phrase, function(){
$("#loadingImage").hide(); // hide the image after loading of div completes
});
Div for your loading image
<div id="loadingImage">
<img src="loader.gif">
</div>
There is a complete callback of jQuery .load function (read more http://api.jquery.com/load/)
You could revise your javascript as following:
<script>
$(document).ready(function () {
$("#textBox").focusout(function () {
var phrase= $("#textBox").val();
phrase= phrase.replace(new RegExp(/\s+/, 'g'), "%20");
ShowLoading();
$("#commentDiv").load(
"../Search/SearchSingular?phrase=" + phrase,
function () { HideLoading(); }
);
});
});
</script>
I'm trying to load an element only after the img element has been loaded, but I've tried everything I can think of and nothing is working. Right now I'm trying to see where the code stops working and I found that the alert I set up isn't running after the line I need the code to execute from.
$img = $('#picture');
function bubbleOnLoad() {
$(document).ready(function() {
$img.load(function(){
alert('document loaded')
$('#left-bubble').show();
})
})
The $img is defined within a function. The alert works at the document.ready line but not after the $img.load. I have tried to add eventlisteners, jquery .on, .load, and a bunch of others. I'm also calling the function to run within my init function. Can someone explain to me why nothing is working?
function choosePic()
$('.speechbubble').hide();
$('#picture').remove();
var randomNum = Math.floor(Math.random() * samplePics.length);
var img = new Image();
img.onload = function() {
$('.playing-field').prepend(img);
handleImageLoad();
}
img.src = samplePics[randomNum];
img.id = "picture";
}
var samplePics =
"assets/images/barack-obama.jpg",
"assets/images/donald-trump_3.jpg",
"assets/images/dt-2.jpg",
"assets/images/bill-clinton.jpg",
"assets/images/Rose-Byrne.jpg",
"assets/images/pic.jpeg",
"assets/images/priest.jpg",
"assets/images/tb.jpg",
"assets/images/test.jpg",
"assets/images/amy-poehler.jpg",
"assets/images/stephen-colbert.jpg",
"assets/images/aziz-ansari.jpg"
];
You had some syntax errors in your code which I corrected and came up with this:
function bubbleOnLoad() {
$img = $('#picture');
$img.load(function () {
alert('document loaded');
$('#left-bubble').show();
});
}
$(document).ready(function () {
bubbleOnLoad();
});
Here is the JSFiddle demo
In you code you are not even telling the browser it's supposed to run a code after image load. you should do something like this:
$(function(){
// DOM Content is ready, let's interact with it.
$('#picture').attr('src', 'image.jpg').load(function() {
// run code
alert('Image Loaded');
});
});
Also according to docs a common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache
Try this jQuery plugin waitForImages
https://github.com/alexanderdickson/waitForImages
//Javascript/jQuery
$(document).ready(function(){
var counter = 0,totalImages= $('#preloader').find('img').length;
$('#preloader').find('img').waitForImages(function() {
//fires for all images waiting for the last one.
if (++counter == totalImages) {
$('#preloader').hide();
yourCallBack();
}
});
});
/*css*/
#preloader{
position:absolute;
top:-100px;/*dont put in DOM*/
}
#preloader > img{
width:1px;
height:1px;
}
<!--HTML [add the plugin after jQuery] -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.waitforimages/1.5.0/jquery.waitforimages.min.js" ></script>
<!--HTML [after body start] -->
<div id=preloader>
<img src="1.jpg" />
<img src="2.jpg" />
<img src="3.png" />
<img src="4.gif" />
<img src="5.jpg" />
</div>
You can only access the HTML element after it was created in DOM.
Also you need to check if the image was loaded before showing.
Thus your code need to look something as below:
$(document).ready(function() {
bubbleOnLoad();
});
function bubbleOnLoad() {
var newSrc = "https://lh5.googleusercontent.com/-lFNPp0DRjgY/AAAAAAAAAAI/AAAAAAAAAD8/Fi3WUhXGOY0/photo.jpg?sz=328";
$img = $('#picture');
$img.attr('src', newSrc) //Set the source so it begins fetching
.each(function() {
if(this.complete) {
alert('image loaded')
$('#left-bubble').show();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="left-bubble" style="display:none">
<img id="picture"/>
</div>
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");
I wanted to load the default image if the user's one didn't exist. I tried this but it didn't work.
$('#avatar').load(function(){
// ... loaded
}).error(function(){
// ... not loaded
$(this).attr('src','/images2/no-avatar2.png');
});
Anyone know how I could do this?
Someone uses this:
function loadDefault(f, ff) {
img = document.getElementById(f);
if(!img.complete) {
img.src = ff;
}
if(typeof(img.naturalWidth) != "undefined" && img.naturalWidth == 0) {
img.src = ff;
}
}
function init() {
setTimeout("loadDefault('side_avatar', '/images/default/avatar_player_profile.gif')", 100);
setTimeout("imageResize(740)", 100);
tooltip = new ToolTip();
tooltip.init('hoverBox', 'loading...');
}
How could I use something like this?
It looks like you are missing your load url as the first parameter of the load() function. Also, without seeing your HTML, I'll assume #avatar is an img tag the way you are using it in the error function. I don't think you can load HTML into an img so you may be better off structuring your html and js like so:
HTML Example:
<div id="avatarDiv">
<img id="avatar" src="" alt="" />
</div>
JS Example:
$('#avatarDiv').load('avatar.php', function() {
// ... loaded
}).error(function() {
// ... not loaded
$('img#avatar').attr('src','/images2/no-avatar2.png');
});
Then just make sure your avatar.php file returns the full html of the image object:
<img id="avatar" src="successful-avatar.jpg" alt="" />
Docs: http://api.jquery.com/load/
I'd try something like this:
$.get("get-avatar.php", function(response) {
$("#avatar").attr('src', response);
}).error(function(response) {
$(this).attr('src', '/images2/no-avatar2.png');
})
as long as avatar.php returns a http error message if the image doesn't exist.
This routine uses ajax to see if the image file exists:
HTML:
<img id='avatar' src='/images2/avatar2find.png' alt='No Image Available'></img>
Script:
$(window).load(function() {
var $img = $('#avatar');
$.ajax({
url: $img.attr('src'),
type: 'get',
statusCode: {
404: function() {
$img.attr('src', '/images2/no-avatar2.png');
}
},
error:
function() {
// do something?
}
});
});