I have this HTML:
<a onmouseover="coverLookout(this,0)" style="width:100%;overflow:hidden" href="#jtCr4NsVySc" class="youtube">
<img id="video_642" style="width:100%;margin-left:0;max-width:100%;visibility:visible" src="https://img.youtube.com/vi/jtCr4NsVySc/mqdefault.jpg">
<span></span>
</a>
And js:
var yt=new Array('maxresdefault.jpg','mqdefault.jpg');
var coverLookout = function(block,i){
console.log(i);
var code=$(block).attr('href').toString().substr(1);
var url = "https://img.youtube.com/vi/" + code + "/" + yt[i];
$(function($){
$.ajax({
url: "function_js.php?page=check_img",
data: {"url":url},
cache: false,
success: function(response){
console.log(response);
if(response=="200"){
$(block).find("img").attr('src',url);return;
}else{
coverLookout(block,++i);
}
}
});
});
};
How can I use coverLookout function while *a* is loading instead of onmouseover? *A* onload doesn't work because onload I can use only with *body*. But how do onload for other tags?
A onload doesn't work because onload I can use only with body. But how do onload for other tags?
No, it works for elements that have a load event. a doesn't have a load event because it never has something to load. All a content is inline. load relates to things like images and scripts and stylesheets and such, that load a separate resource.
img has a load event, if you're talking about the image inside the link loading. You have to be sure to hook the event before setting the img source (the onload attribute works), or check the complete flag on the element if hooking the event later to see if it's already done.
From the comments below, it sounds like you want to change the img's source when the link is clicked. You can do that like this:
<a onclick="document.getElementById('video_642').src = '/new/src/here.png' ...
...or as you're using jQuery, this will handle all youtube links:
$("a.youtube").click(function() {
$(this).find("img").attr("src", "/new/src/here.png");
});
But the user may not see it, because when the link is followed, the browser tears down the page right away. You can improve the chances your user will see it if you make sure it's already in cache, by putting it on your page somewhere but hidden:
<img style="display: none" src="/new/src/here.png">
...so the browser has it in cache to display it before tearing down the page.
I want to while page is loading src in img will be changed by script
You mean when the page these links are on is loading? Okay. This would go in a script tag at the end of the body (just before the closing </body> element:
// Find all images within a.youtube links and change their `src`
$("a.youtube img").each(function() {
var img = $(this);
// Save current src so we can put it back later
img.attr("data-real-src", this.src);
// Set new source
this.src = "/new/src/here.png";
});
// Then when the page is done loading...
$(window).on("load", function() {
// Restore the original `src` values on the images
$("img[data-real-src]").each(function() {
var img = $(this);
img.attr("src", img.attr("data-real-src")).removeAttr("data-real-src");
});
});
onload Function works only with <body> so after document loading (under $(document).ready() function collect all a tags and call the function based on their index.
var els = document.getElementsByTagName("a");
for(var i = 0, l = els.length; i < l; i++) {
coverLookout(els[i],i);
}
Related
I have a page where an image with a wrapping div gets loaded via ajax. I need to apply some code when that image is loaded. I cannot alter the ajax call so I cannot simply use on('success') on the ajax call.
After some time the image with the div gets reloaded the same way (it is a kind of rotation).
The structure is like this:
<div id="spot">
<div id="xyz">
<a href="http://someurl.com">
<img src="http://someimage.url" />
</a>
</div>
</div>
The "spot" div is fixed and everything inside of it gets loaded dynamically.
When I put in
$('#xyz img').on('load', myCallback);
It doesn't work, I think because when the image gets reloaded, the listener is also removed.
I tried with the delegated listener:
$('#spot').on('load', '#xyz img', myCallback);
but didn't work either, it doesn't get executed (I've put console.log inside to verify what happens).
When I type in console $('#spot #xyz > img') the console shows the correct object.
How can I run my myCallback function right after the dynamic content with the image is ready for some DOM scripting action?
If you can't get access to the AJAX request callback then your options are limited to a setInterval() timer which checks to see if the elements have been added, a MutationObserver or a load event on an img element - but be aware this will only fire after the src of the image has loaded so there will be a delay.
Here's how you can use the MutationObserver, but be aware this will only work for newer browsers:
var targetElement = document.querySelector('#container');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// perform the required actions here...
console.log(mutation.type);
});
});
observer.observe(targetElement, { attributes: true, childList: true, characterData: true });
Not the correct way but you can try this
var handle = setInterval(showImage, 500);
function showImage(e) {
var img = $('#spot').find("img");
if(img != undefined) {
if($(img).is(":visible")) {
clearInterval(handle);
handle = 0;
// your logic
}
}
}
I need to load an image, js need to get link url and print this image on screen.
But it is not working.
What is wrong with my script? what can I do to make it work and improve it?
html
<div id=img></div>
<div id=loading></div>
<a href=http://png-5.findicons.com/files/icons/1580/devine_icons_part_2/128/my_computer.png class=postmini>Open image 1</a>
<br>
<a href=http://www.iconshock.com/img_jpg/BETA/communications/jpg/256/smile_icon.jpg class=postmini>Open image 2</a>
js
$(function() {
$(".postmini").click(function(){
var element = $(this);
var I = element.attr("href");
$("#loading").html('<img src="loader.gif" align="absmiddle"> loading...');
$("#loading").ajaxComplete(function(){}).slideUp();
$("#img").append(I);
});
});
https://jsfiddle.net/u6j2udzb/
and this loading div, what I need to do to make it work properly?
You are missing a lot and have a lot you don't need. I have commented out where you don't need items. In particular you don't need a loading because the image will be there before they see that. However, if you do want it still, you should be loading it underneath the image you are loading. So it gets covered by the image. I can update it with that if you'd like.
What you are missing is actual code to turn the href into an image source and you are not removing the default action of the anchor tag so it doesn't try loading a new page when clicked.
$(".postmini").click(function(event){
event.preventDefault();
var element = $(this);
var I = element.attr("href");
//$("#loading").html('loading...');
//$("#loading").ajaxComplete(function(){}).slideUp();
// remove old image if it is already there.
$("#img").empty();
// create variable holding the image src from the href link
var img = $("<img/>").attr("src", I)
$("#img").append(img);
});
https://jsfiddle.net/3g8ujLvd/
You just have to insert an img tag into your "display div" on click on the link... to load the image... (btw your syntax errors are terrible... you have to use quotes for attributes^^)
like this for example :
$('.postmini').on('click',function(){
//do something
});
Check this : https://jsfiddle.net/u6j2udzb/8/
(done quickly for example)
Hope it helps
You are not running an ajax script. ajaxComplete is only fired after an ajax script completed.
Whenever an Ajax request completes, jQuery triggers the ajaxComplete
event. Any and all handlers that have been registered with the
.ajaxComplete() method are executed at this time.
You should ad an ajax script and than ajaxComplete will run if you registered the ajaxComplete method.
At the moment you're just placing the text from the "href" attribute on the link into the div. You need to either create an image or use the link provided as a background.
The quickest way to see this is to change make this change:
var element = $(this);
var I = element.attr("href");
$("#loading").html('<img src="loader.gif" align="absmiddle"> loading...');
$("#loading").ajaxComplete(function(){}).slideUp();
// $("#img").append(I);
$("#img").html("<img src='"+I+"' />");
$('.postmini').on('click',function(e){
e.preventDefault();
$('#loading').html('<img src="'+this.href+'">').children('img').one('load',function(){$(this).parent().slideUp('slow');});
});
Noticed I used on instead of click this allows you to use this.href rather than a more lengthy $(this).attr('href'). I also used .one on a child image element to find out if the image has loaded.
But I've just realised that this is useless because you want to have a loader. Ma bad.
$('.postmini').on('click',function(e){
e.preventDefault();
//best have the loader.gif showing on default before the load is complete.
var img=$('<img class="loadedImage">');
img.src=this.href;
//img.css({display:none;});//remove this if you've enter CSS .loadedImage{display:none;}
$('#loading').append(img).slideDown('slow',function(){$(this).children('.loadedImage').one('load',function(){$(this).fadeIn('slow');$(this).siblings('img[src="loader.gif"]').hide();});});
});
This method is what you're looking for. Basically you want to click the link, stop the default action of going to the link, make a new image element and set the src, make sure it's hidden before load, add the new image element to loading, slide up parent loading, check for load and fade in :)
Try and run this simple snippet
$('#myButton').click(()=>{
let imgUrl = $('#imgUrl').val();
$.get(imgUrl)
.done(() => {
$('img').attr('src', imgUrl);
$('#imgText').text('');
})
.fail(() => {
$('#imgText').text('Image does not exist');
$('img').attr('src', '');
})
})
img {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Image url: <input type="text" id="imgUrl" value="https://upload.wikimedia.org/wikipedia/commons/7/75/Woman_mechanic_working_on_engine_%28cropped%29.jpeg"><br>
<button id="myButton" type="button">click here to load image</button>
<div id="imgText"></div>
<img>
I have to load image sequence animation about 60 images array. I want this particular sequence loaded separately. means that images loading time does not affected to whole page load time. because it is taking too much time to load page with image sequence animation. Currently i have added all 60 images of sequence in HTML code and set "display:none" to load with page.
Is there any possibility to load this images separately or load after my whole html page loaded. or any other better solution.
Thanks in advance.
Load them dynamically using javascript/jquery
var imagePaths = ["img1.png", ....];
$(document).ready(function(){
for(var i=0; i<imagePaths.length; i++) {
var newImg = $('<img style="display:none;" />'); //Add any class or attribute you want or anything for images.
newImg.bind("load", function(){
$(this).show();
});
newImg.attr("src", imagePaths[i]);
$(parentSelector).append(newImg);
}
});
When you load dynamically from script, your HTML page would have loaded and be ready for use. And later all the images will come into view gradually.
Edit:
In addition if you want to keep your image hidden until it gets completely loaded, you could initially set display:none; inline and attach an onload listener, display:block there.
Hope this helps. Let me know if I missed anything.
Yes it is possible.
var images[60];
var names[60]={"img1.jpg","img2.jpg"...}
function loadImages() {
for(var i=0;i<60;i++) {
images[i] = new Image();
images[i].src = "www.myWebPage.com/"+names[i];
}
}
This function will now load images. Just make sure to call it after your page loads.
<body onLoad="loadImages()">
...
</body>
I have an html file that I want to be loaded from various pages into a dijit.contentpane. The content loads fine (I just set the href of the contentpane), but the problem is that javascript within the html file specified by href doesn't seem to be executed at a consistent time.
The final goal of this is to load an html file into a contentpane at an anchor point in the file (i.e. if you typed in index.html#tag in order to jump to a certain part of the file). I've tried a few different methods and can't seem to get anything to work.
What I've tried:
1.
(refering to the href of the dijit.contentpane)
href="page.htm#anchor"
2.
(again, refering to the href of the dijit.contentpane -- didn't really expect this to work, but decided to try anyways)
href="#anchor"
3. (with this last try inside the html specified by href)
<script type="text/javascript">
setTimeout("go_to_anchor();", 2000);
function go_to_anchor()
{
location.href = "#anchor";
}
</script>
This last try was the closest to working of all of them. After 2 seconds (I put the delay there to see if something in the dijit code was possibly loading at the same time as my javascript), I could see the browser briefly jump to the correct place in the html page, but then immediately go back to the top of the page.
Dojo uses hashes in the URL to allow bookmarking of pages loaded through ajax calls.
This is done through the dojo.hash api.
So... I think the best thing you can do is use it to trigger a callback that you write inside your main page.
For scrolling to a given position in your loaded contents, you can then use node.scrollIntoView().
For example, say you have a page with a ContentPane named "mainPane" in which you load an html fragment called "fragment.html", and your fragment contains 2 anchors like this :
-fragment.html :
Anchor 1
<p>some very long contents...</p>
Anchor 2
<p>some very long contents...</p>
Now say you have 2 buttons in the main page (named btn1 and btn2), which will be used to load your fragment and navigate to the proper anchor. You can then wire that up with the following javascript, in your main page :
<script type="text/javascript">
require(['dojo/on',
'dojo/hash',
'dojo/_base/connect',
'dijit/layout/BorderContainer',
'dijit/layout/ContentPane',
'dijit/form/Button'],
function(on, hash, connect){
dojo.ready(function(){
var contentPane = dijit.byId('mainPane');
var btn1 = dijit.byId('btn1');
var btn2 = dijit.byId('btn2');
btn1.on("Click", function(e){
if (!(contentPane.get('href') == 'fragment.html')) {
contentPane.set("href", "fragment.html");
}
hash("anchor1");
});
btn2.on("Click", function(e){
if (!(contentPane.get('href') == 'fragment.html')) {
contentPane.set("href", "fragment.html");
}
hash("anchor2");
});
// In case we have a hash in the URL on the first page load, load the fragment so we can navigate to the anchor.
hash() && contentPane.set("href", "fragment.html");
// This callback is what will perform the actual scroll to the anchor
var callback = function(){
var anchor = Array.pop(dojo.query('a[href="#' + hash() + '"]'));
anchor && anchor.scrollIntoView();
};
contentPane.on("DownloadEnd", function(e){
console.debug("fragment loaded");
// Call the callback the first time the fragment loads then subscribe to hashchange topic
callback();
connect.subscribe("/dojo/hashchange", null, callback);
});
}); // dojo.ready
}); // require
</script>
If the content you're loading contains javascript you should use dojox.layout.ContentPane.
Does the IFRAME's onload event fire when the HTML has fully downloaded, or only when all dependent elements load as well? (css/js/img)
The latter: <body onload= fires only when all dependent elements (css/js/img) have been loaded as well.
If you want to run JavaScript code when the HTML has been loaded, do this at the end of your HTML:
<script>alert('HTML loaded.')</script></body></html>
Here is a relevant e-mail thread about the difference between load and ready (jQuery supports both).
The above answer (using onload event) is correct, however in certain cases this seems to misbehave. Especially when dynamically generating a print template for web-content.
I try to print certain contents of a page by creating a dynamic iframe and printing it. If it contains images i cant get it to fire when the images are loaded. It always fires too soon when the images are still loading resulting in a incomplete print:
function printElement(jqElement){
if (!$("#printframe").length){
$("body").append('<iframe id="printframe" name="printframe" style="height: 0px; width: 0px; position: absolute" />');
}
var printframe = $("#printframe")[0].contentWindow;
printframe.document.open();
printframe.document.write('<html><head></head><body onload="window.focus(); window.print()">');
printframe.document.write(jqElement[0].innerHTML);
printframe.document.write('</body></html>');
// printframe.document.body.onload = function(){
// printframe.focus();
// printframe.print();
// };
printframe.document.close();
// printframe.focus();
// printframe.print();
// printframe.document.body.onload = function()...
}
as you can see i tried out several methods to bind the onload handler... in any case it will fire too early. I know that because the browser print preview (google chrome) contains broken images. When I cancel the print and call that function again (images are now cached) the print preview is fine.
... fortunately i found a solution. not pretty but suitable. What it does that it scans the subtree for 'img' tags and checking the 'complete' state of those. if uncomplete it delays a recheck after 250ms.
function delayUntilImgComplete(element, func){
var images = element.find('img');
var complete = true;
$.each(images, function(index, image){
if (!image.complete) complete = false;
});
if (complete) func();
else setTimeout(function(){
delayUntilImgComplete(element, func);}
, 250);
}
function printElement(jqElement){
delayUntilImgComplete(jqElement, function(){
if (!$("#printframe").length){
$("body").append('<iframe id="printframe" name="printframe" style="height: 0px; width: 0px; position: absolute" />');
}
var printframe = $("#printframe")[0].contentWindow;
printframe.document.open();
printframe.document.write(jqElement[0].innerHTML);
printframe.document.close();
printframe.focus();
printframe.print();
});
}
Just when the html loads, not the dependent elements. (or so I think).
To fire when the rest of the page loads do jQuery(window).load(function(){ or window.onload not document onready.
You can also check to see if an image element is loaded and there... if image . load-- etc.