I'm trying to get an user input image to refresh say every two seconds. The javascript gets user input for an URL and the javscript adds it to the page. Then the images loaded need to refresh every 2 seconds but i can't get it to refresh properly without refreshing the whole page or reloading from the cache:
function getImg(){
var url=document.getElementById('txt').value;
var div=document.createElement('div');
div.className="imageWrapper";
var img=document.createElement('img');
img.src=url;
div.appendChild(img);
document.getElementById('images').appendChild(div);
return false;
}
setInterval(function(){
$('img').each(function(){
var time = (new Date()).getTime();
$(this).attr("src", $(this).attr("src") + time );
});
}, 2000);
any ideas?
When you need to force reload the resource, you have to add a dymmy queryString at the end of your url:
<img id="img1" src="myimg.png?dummy=23423423423">
Javascript:
$('#img1').attr('src','myimg.png?dummy=23423423423');
and change the dummy value for each refresh
Your premise seems good, not sure why it isn't working. Why mixing and matching jQuery with non-jquery? This is a modification of your code, but it is a working example. You should be able to adapt it for your purpose.
http://jsfiddle.net/zr692/1/
You can create elements via jQuery easily. See the modified getImg function I created. Ia also switched from attr to prop which is the recommended means of accessing the src attribute in jQuery 1.7+.
function getImg() {
var url = 'http://placehold.it/300x300/123456';
var $div = $('<div />');
var $img = $('<img />', { src: url });
$div.append($img);
$('body').append($div);
}
getImg();
var interval = setInterval(function() {
$('img').each(function() {
var time = (new Date()).getTime();
var oldurl = $(this).prop('src');
var newurl = oldurl.substring(0, oldurl.lastIndexOf('/') + 1) + time.toString().substr(7, 6);
$('#output').html(newurl);
$(this).prop('src', newurl);
});
}, 2000);
Put the image in a container as:
<div id="container"><img src=""../> </div>
then simply update the content of the container as:
$('#container').html('<img src="newSource"../>');
Related
I am trying to stream live image to my webpage. When the image content is being updated at backend, sometimes the path may return invalid content. How do I detect the URL contains invalid content, and thus do not refresh my image ?
My current implementation of image update:
function update(){
$("#live").prop("src", "/HTTPGetImage?ImageIndex=0?"+ +new Date());
setTimeout(update, 3000);
}
I've tried to use .get() to check if return data is valid.
$.get('/HTTPGetImage?ImageIndex=0?').done(function(data)
{
if(data!="")
$("#live").prop("src", "/HTTPGetImage?ImageIndex=0?"+ +new Date());
})
But this approach doesn't work. I think the updating is very frequent at backend, so between my first and second request to server, image at back-end might already been updated. What should I do to avoid getting invalid content, and if I get invalid content, how do I preserve current img src ?
You can create a pseudo image with jquery that you will not attach to DOM, and hook into it's load and error events. My example shows how this can be achieved - just implement your logic into onerror and onload handlers - if it loads, you can set your image, if error is triggered, show previous.
$(document).ready(function(){
var last_image = 0
var sample_images = ["https://via.placeholder.com/100",
"https://via.placeholder.com/101/000/fff",
"https://via.placeholder.com/error",
"https://via.placeholder.com/103/880000/fff"]
function loadImage(){
var next_image = (last_image == sample_images.length-1)?0:last_image+1
setTimeout(function(){
var pseudoImg = $("<img>");
pseudoImg.attr("src",sample_images[next_image])
pseudoImg.on("load",function(){
$("#img").attr("src",sample_images[next_image])
$("#url").html(sample_images[next_image])
last_image=next_image
loadImage()
});
pseudoImg.on("error",function(){
// not changing previous image
$("#url").html("ERROR LOADING "+sample_images[next_image]+"<br> displaying previous: "+sample_images[last_image])
last_image=next_image
loadImage()
})
},2000)
}
loadImage()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://via.placeholder.com/100" id="img">
<div id="url">https://via.placeholder.com/100</div>
For your example the code would be something like this:
function update(){
setTimeout(function(){
var timestamp = new Date()
var url = "/HTTPGetImage?ImageIndex=0?"+timestamp
var pseudoImg = $("<img>");
pseudoImg.attr("src",url)
pseudoImg.on("load",function(){
$("#live").attr("src",url)
update()
});
pseudoImg.on("error",function(){
// don't do nothing, just call next update
update()
})
},3000);
}
(not duplicate, because not find exactly/easy solution)
I'm trying to execute JS after all images completely loaded. My goal is, when all images finish load completely, then removeClass my-loader and addClass visible to main-slider div.
HTML:
<div class='main-slider my-loader'>
<img src="https://unsplash.it/200/300/">
<img src="https://unsplash.it/200/300/">
<img src="https://unsplash.it/200/300/">
</div>
Execute below js when all images completely loaded
$(".main-slider").removeClass("my-loader").addClass("visible");
Tried this js :
But not works properly on my site, problem is when i clear browser cache, then it works/execute! when i reload page then next time it's not works/execute! It only works when i clear browser cache.
var img = $('.main-slider img')
var count = 0
img.each(function(){
$(this).load(function(){
count = count + 1
if(count === img.length) {
$('.main-slider').removeClass('my-loader').addClass('visible')
}
});
});
Any simple solution? Thanks in advance.
jQuery provides a way to register a callback for the window load event which will fire when the entire page, including images and iframes, are loaded.
Reference: https://learn.jquery.com/using-jquery-core/document-ready/
Your code should look something like:
$( window ).load(function () {
var img = $('.main-slider img')
var count = 0
img.each(function(){
$(this).load(function(){
count = count + 1
if(count === img.length) {
$('.main-slider').removeClass('my-loader').addClass('visible')
}
});
});
});
Here's how to do this, using Deferreds and native handlers, and calling the onload handler if the image is cached in older browsers etc.
var img = $('.main-slider img');
var defs = img.map(function(){
var def = new Deferred();
this.onload = def.resolve;
this.onerror = def.reject;
if (this.complete) this.onload();
return def.promise();
});
$.when.apply($, defs).then(function() {
$('.main-slider').removeClass('my-loader').addClass('visible')
});
I'm creating a iFrame DOM dynamically only for printing. Here's my code doing the creation and show printing window.
var url, data, _iFrame, nonce, iframeId;
data = new Blob([buffer], {
type: 'application/pdf'
});
url = window.URL.createObjectURL(data);
_iFrame = document.createElement('iframe');
nonce = (new Date()).getTime();
var iframeId = "printPDF" + nonce;
_iFrame.id = iframeId
_iFrame.setAttribute('style', 'visibility:hidden;');
_iFrame.setAttribute('src', url);
document.body.appendChild(_iFrame);
$('#' + iframeId)[0].focus();
$('#' + iframeId)[0].contentWindow.print();
But the thing is, I need to remove the iFrame after the printing is done (either print or cancel). How can I get the event in javascript?
I guess something like this will do the work for you:
$('#' + iframeId)[0].contentWindow.print();
setTimeout(function () { $('#' + iframeId)[0].contentWindow.close(); }, 100);
I actually resolved this on my own.
The first thing is not to hide the iframe. Instead, make it 0 size. style='height: 0;width: 0;'.
Then, bind the focus event of the iframe and remove the iframe when it's focused again after the print dialog gets dismissed.
Well, I tried the focus event, and I failed to get into it because the iframe was hidden.
I'm new to jQuery and JS. How can I rewrite these functions correctly using jQuery? I know it's standard JS which was working fine with the manual HTML markup but I now also need to go through page and find iframes with YouTube src and take ID and then recreate them with the first example markup.
I'm totally stuck. I think I have it more or less, but not sure where to go to now.
Fiddle: https://jsfiddle.net/yurt5bb6/
First example uses my markup:
<div class="video-container">
<div class="video-player" data-id="Cv_2mp3X868"></div>
</div>
Which works as I need, however I think now I need to foreach on load and create that same markup from iframe embeds the functions should be better.
Attempt:
function createThumb(id) {
return '<img class="youtube-thumb" src="//i.ytimg.com/vi/' + id + '/hqdefault.jpg"><div class="play-button"></div>';
}
function createIframe() {
var iframe = $("iframe");
iframe.attr("src", "//www.youtube.com/embed/" + this.parentNode.dataset.id + "?autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&controls=0&showinfo=0");
iframe.attr("frameborder", "0");
iframe.attr("id", "youtube-iframe");
this.parentNode.replaceChild(iframe, this);
}
$(document).ready(function() {
// build video from default markup
var defaultVideo = $(".video-player");
$(defaultVideo).each(function (index, value){
var p = $('<div></div>');
p.innerHTML = createThumb(v[n].dataset.id);
p.onclick = createIframe;
v[n].appendChild(p);
});
// search for social embeds and recreate to our markup
$('iframe[src*="youtube.com"]').each(function() {
var loadedVideoURL = $('iframe').attr('src').match(/[^/]*$/)[0];
console.log(loadedVideoURL);
});
});
I've tried to clean up the messy mix of native JS and jQuery and made some edits to your fiddle: https://jsfiddle.net/yurt5bb6/2/
Default function:
(function() {
$.each($('.video-player'), function() {
$(this).append(videoThumb($(this).data('id')));
$(this).on('click', videoIframe);
});
$.each($('iframe'), function() {
// Rebuild the given template
var player = $('<div class="video-player">');
// Strip youtube video id for data-id attribute
var id = $(this).attr('src');
id = id.substr(id.lastIndexOf("/")+1);
player.attr('data-id', id);
player.html(videoThumb(id));
player.on('click', videoIframe);
var videoContainer = $('<div class="video-container">');
videoContainer.append(player);
$(this).replaceWith(videoContainer);
});
})();
Iframe render function:
function videoIframe() {
var iframe = $('<iframe>');
iframe.attr("src", "//www.youtube.com/embed/" + $(this).attr('data-id') + "?autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&controls=0&showinfo=0");
iframe.attr("frameborder", "0");
iframe.addClass("youtube-iframe");
$(this).empty();
$(this).append(iframe);
}
Also changed the CSS, made a class instead of id for youtube-iframe.
also threw it up on jsbin: http://jsbin.com/ohazo/2
but the code on jsbin is the old code, so overlay_nextimg is overlay_content.click in the javascript on jsbin
Jquery lightbox, grab next link from the one we just clicked, take it's href, fade out the current image, and load in the next img.
Also, how would i go about keeping the overlay_content centered? when changing images, have it animate to the new position? i was gonna tackle that next, but i'm here so why not.
Jquery and Html, i've changed the overlay_content.click that we were using before to overlay_nextimg, to be less confusing.
Jquery:
$(function (){
$('a.lightbox').click(function() {
var imghref = $(this).attr("href");
loadImage(imghref);
alert(imghref)
return false;
});
$('.overlay_nextimg').click(function (){
var currlink = $("a[href='" + $(".overlay_content img").attr("src") + "']");
var nextlink = $(currlink).next(".lightbox");
var prevlink = $(currlink).prev(".lightbox");
alert(nextlink);
loadImage(nextlink);
});
$('.overlay_previmg').click(function (){
var currlink = $("a[href='" + $(".overlay_content img").attr("src") + "']");
var nextlink = $(currlink).next(".lightbox");
var prevlink = $(currlink).prev(".lightbox");
alert(prevlink);
loadImage(prevlink);
});
function loadImage(href, prevlink, nextlink) {
var currentImg = $('.overlay_content img');
var img = new Image();
var docHeight = $(document).height();
$('.overlay_content').delay(300).fadeIn(400);
$(".overlay_bg").height(docHeight).fadeIn(400, function(){
$(img).load(function () {
$(img).hide();
$('.overlay_content').html(img);
$(img).fadeIn('slow');
}).error(function () {
$('.overlay_content').html("you SUCK at Javascript")
}).attr('src', href);
})
}
$('.overlay_bg').click(function (){
$(this).fadeOut(300);
$(".overlay_content").fadeOut(300, function(){
$(this).html('');
});
});
});
HTML:
<div class="overlay_bg"></div>
<div class="overlay_content"></div>
<h1>links</h1>
Load a water color image.
Load a library book, yeah.
from the interweb.
internet image.
HUGE
Please add more of the code/HTML - Is $("overlay_content").click(...) the function you need to fix?
You can use the eq() selector to get the n-th a.lightbox on the page. But obviously you'll need to track what link you're currently on., i.e.
$("a.lightbox:eq(1)")
Or - using the src of the image currently being displayed, find out which link was clicked and move next from there, i.e.
$("a.lightbox[href='" + currentImg.attr("src") + "']").next()