Banner rotator giving "loading" message in browsers - javascript

I have this banner rotator function:
var banners = ['../Graphics/adv/1.gif','../Graphics/adv/2.jpg']; //here put location of the files to display
var loadedImgSrc = null;
function loadBanner() {
var liczba = Math.floor(Math.random()*banners.length);
loadedImgSrc = banners[liczba];
var objImage = new Image();
objImage.onLoad=imagesLoaded();
objImage.src = banners[liczba];
}
function imagesLoaded() {
document.getElementById('ad_banner').src = loadedImgSrc;
startRotator();
}
function startRotator() {
setTimeout('loadBanner()',8000); //here, set up interval in miliseconds 1000ms -> 1s
}
This is giving a "loading" message, as if the browsers are continuously loading.
Does anybody have a simple banner-rotator to share?
Or does anybody know whats wrong with this one?
Thanks

Take a look at this custom animated banner made with jQuery. There are both horizontal and vertical versions.

Related

Can I "freeze" fixed elements to take a screenshot with getDisplayMedia?

I'm implementing a chrome extension with javascript to take a screenshot of a full page, so far I've managed to take the screenshot and make it into a canvas in a new tab, it shows the content of a tweet perfectly, but as you can see, the sidebars repeat all the time (Ignore the red button, that's part of my extension and I know how to delete it from the screenshots) screenshot of a tweet
This is the code I'm using to take the screenshot:
async function capture(){
navigator.mediaDevices.getDisplayMedia({preferCurrentTab:true}).then(mediaStream=>{
scrollTo(0,0);
var defaultOverflow = document.body.style.overflow;
//document.body.style.overflow = 'hidden';
var totalHeight = document.body.scrollHeight;
var actualHeight = document.documentElement.clientHeight;
var leftHeight = totalHeight-actualHeight;
var scroll = 200;
var blob = new Blob([document.documentElement.innerHTML],{ type: "text/plain;charset=utf-8" });
console.log('total Height:'+totalHeight+'client height:'+actualHeight+'Left Height:'+leftHeight);
var numScreenshots = Math.ceil(leftHeight/scroll);
var arrayImg = new Array();
var i = 0;
function myLoop() {
setTimeout(function() {
var track = mediaStream.getVideoTracks()[0];
let imgCapture = new ImageCapture(track);
imgCapture.grabFrame().then(bitmap=>{
arrayImg[i] = bitmap;
window.scrollBy(0,scroll);
console.log(i);
i++;
});
if (i <= numScreenshots) {
myLoop();
}else{
document.body.style.overflow = defaultOverflow;
saveAs(blob, "static.txt");
printBitMaps(arrayImg, numScreenshots, totalHeight);
}
}, 250)
}
myLoop();
})
}
async function printBitMaps(arrayImg, numScreenshots, totalHeight){
var win = window.open('about:blank', '_blank');
win.document.write('<canvas id="myCanvas" width="'+arrayImg[0].width+'px" height="'+totalHeight+'px" style="border:5px solid #000000;"></canvas>');
var e = numScreenshots+1;
function printToCanvas(){
setTimeout(function(){
var canvas = win.document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(arrayImg[e], 0, 200*e);
e--;
if(e>=0){
printToCanvas();
}
},10);
}
printToCanvas();
}
Do you know any way by CSS or javascript that I can use to make the sidebars stay at the top of the page so they don't keep coming down with the scroll?
It's not really a case of "the sidebars ... coming down with the scroll" - the code you're using is taking a first screenshot, scrolling the page, taking another screenshot and then stitching it onto the last one and iterating to the bottom of the page. Thus it's inevitable you're seeing what you see on the screen at the point you take the subsequent screenshots.
To resolve your issue, after your first screenshot you would need to set the div element for the side bar to be display=None by use of CSS. You can find details of the side bar by using the browser Dev Tools, right clicking an using "Inspect" in Chrome.
From what I can see, Twitter seems to use fairly cryptic class names, so it might be easiest and more robust to identify the div for the side bar with some other attribute. It appears they set data-testid="sidebarColumn" on it so give using that a go (but YMMV).

Images not preloaded properly

I am having a jQuery script that loads 15 images and their hover versions (the hover versions are used when... hovering, not when the page loads). In both Chrome and Firefox in the Network tab, i see this :
images/img1.png
images_hover/img1.png
This must mean the hover images are preloaded correctly, but... when i actually hover and those images are used, they are being loaded again. Here is the preload code :
var prel = new Image();
prel.src = "http://hdodov.byethost15.com/color-game/graphics/parts_hover/" + id + ".png";
I tried using the whole path - http://hdodov.byethost15.com/color-game/graphics/parts_hover/ and the short path too (where the root and the script is) - graphics/parts_hover/. It made no difference.
Could this be caused because my images have the same name? They are in different directories though.
For the next question, you really should paste more code, which makes it easier to help you. I checked your URL you provided, but for other people that might have the same problem, it will be hard to understand what went wrong...
OK, as I said, you are always requesting he images again on hover state...
This worked for me:
var context = new Array(15),
canvas = new Array(15),
canvasNum = -1,
hElem,
hElemPrev,
mousePos = {x:-1, y:-1},
images = [], //<-- Store preloaded images here
imagesHover = []; //<-- Store preloaded images here
... then save them on building like this:
function drawMenuItems(id, width, height){
var canNumHolder, createCanvas;
$('#canvas_holder').append($('<canvas></canvas>')
.attr({
width:width,
height:height,
id:id
})
);
canvasNum++;
canvas[canvasNum] = document.getElementById(id);
context[canvasNum] = canvas[canvasNum].getContext('2d');
canNumHolder = canvasNum;
images[id].crossOrigin = 'Anonymous';
images[id].onload = function(){
context[canNumHolder].drawImage(images[id],0,0);
};
images[id].src = 'graphics/parts/' + id + '.png';
//Hover states
imagesHover[id] = new Image();
imagesHover[id].src = "graphics/parts_hover/" + id + ".png";
}
... give just the id...
function hoverStateChange() {
//....rest of the code
if(hElem >= 0){
drawImageOnCanvas(
canvas[hElem],
context[hElem],
"hover", //pass somethink to checke what you want to do
$(canvas[hElem]).attr('id')
);
//....rest of the code
//change to normal texture
if(hElemPrev >= 0){
drawImageOnCanvas(
canvas[hElemPrev],
context[hElemPrev],
"", //pass empty for other state
$(canvas[hElemPrev]).attr('id')
);
$(canvas[hElemPrev]).removeClass('active');
$('#text_holder').removeClass('a' + hElemPrev);
}
.. and finally
function drawImageOnCanvas(canv, contxt, state, src){
contxt.clearRect(0,0,400,400);
if(state == "hover"){
contxt.drawImage(imagesHover[src],0,0);
}else {
contxt.drawImage(images[src],0,0);
}
}
Like this, you chache you images and not calling them again and again...
I hope it helps.
Yuo can preload images with css like this:-
#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }

Jquery to let my banner images load first before it animates

I have created a banner image slideshow in jquery. Actually I just found the code somewhere, I can't remember. It starts to animate even the banner images are not yet fully loaded that makes the banner slideshow animates it's image description without images.
Anyone? please help me to modify the code and let it run by allowing the background images load first before it runs the slideshow animation.
Thank you.
(function ($) {
// Original JavaScript code.
var currentBackground = 0;
var backgrounds = [];
backgrounds[0] = 'http://www.site.com/sites/all/themes/layoutph/images/bg01.jpg';
backgrounds[1] = 'http://www.site.com/sites/all/themes/layoutph/images/bg02.jpg';
backgrounds[2] = 'http://www.site.com/sites/all/themes/layoutph/images/bg03.jpg';
backgrounds[3] = 'http://www.site.com/sites/all/themes/layoutph/images/bg04.jpg';
var customtitle = [];
customtitle[0] = "Welcome to Site";
customtitle[1] = "Site joined force with Site Foundation";
customtitle[2] = "Site Foundation school campaigns for 2014";
customtitle[3] = "New York visited by Site Foundation";
function changeBackground() {
if(currentBackground > 3 ) currentBackground = 0;
currentBackground++;
$('.masterbg').fadeOut(1000,function() {
$('div.slogan').text( customtitle[currentBackground] );
$('.masterbg').css({
'background-image' : "url('" + backgrounds[currentBackground] + "')"
});
$('.masterbg').fadeIn(1000);
});
setTimeout(changeBackground, 4000);
}
setTimeout(changeBackground, 4000);
})(jQuery);
var UserimageObj = new Image();
UserimageObj.src = "someimg.jpg";
//load the user image before doing anything
UserimageObj.onload = function () {
//do your stuff here
};
Is this what you were looking for?

Is this a correct way to preload an image in Javascript / Jquery (with animation)?

Im' trying to display a basic animation while an image loads, in html.
Is this the correct way to do it?
//display the (small image) animation
var preloader = new Image();
preloader.src = 'img/preload.gif';
$('#myDiv').append(preloader);
//load big image and hide peload animation when finished
var img = new Image();
img.onload = function () { $(preloader).hide(); preloader = null; } ;
img.src = 'img/bigImage.jpg';
$('#myDiv').append(img);
I'm not sure that is correct: although it works in my browser, the small animation is always loaded, even if the big image has already been loaded and is in cache. Is there a way to de-activate this, or think or another way to handle the preload of an image with a small animation?
Thanks
Here's how I'd do it:
var preloader = new Image(),
img = new Image(),
div = document.getElementById('myDiv');
img.onload = function () {
preloader = null;
div.innerHTML = '';
div.appendChild(this);
};
img.src = 'img/bigImage.jpg';
// if it's not in cache or not loaded (has no size), show the preloader
if (! (img.complete || img.width+img.height > 0) ) {
preloader.src = 'img/preload.gif';
div.innerHTML = '';
div.appendChild(preloader);
}

Add Delay to Mouseover using Javascript

I'm using the following script for all my image mouseovers:
loadImage1 = new Image();
loadImage1.src="1.jpg";
staticImage1 = new Image();
staticImage1.src="1-roll,jpg";
How can I simply add, say, a second or two delay before it executes the mouseover?
Thanks in advance for your help!
---UPDATE---
Thanks for the replies. Excuse my ignorance when it comes to Javascript. How can I include the timeout piece in the following script?
<SCRIPT LANGUAGE="JavaScript">
loadImage1 = new Image();
loadImage1.src="/wp-content/themes/Anna%20Rawson/images/1-blog.jpg";
staticImage1 = new Image();
staticImage1.src="/wp-content/themes/Anna%20Rawson/images/1-blog.jpg";
</script>
Do I wrap the timeout piece in it's own script tag? Thanks for the quick help!
You can use setTimeout(), an example:
var img1 = document.getElementById('my-img');
img1.onmouseover = function() {
setTimeout(function() {
this.src = 'my-img-2.png';
}, 1000); // 1000ms = 1s delay
};
First of all, your code have some mistakes:
Always write HTML tags in lowercase, not <SCRIPT> but <script>
The langauge attribute is not a valid attribute, use type="text/javascript" instead, or just remove it it isn't required.
And the Image object is not really making an image on the website. It preloads the image, so you can use it on your website without loading it. Like this example:
<img src="/img/my-first-img.png" onmouseover="this.src = '/img/heavy-img.png'">
<script>
var heavyImg = new Image();
heavyImg.src = '/img/heavy-img.png'; // preload the img
</script>
Because we preload the /img/heavy-img.png we can directly see the heavy-img if me mouse over the first-img. If we don't preload the img, it will be loaded when we mouse over.
Instead of using an onmouseover attribute we use the onmouseover event + callback in the JS file. Now we can add a delay:
<img src="/img/my-first-img.png" id="my-img">
<script>
var heavyImg = new Image();
heavyImg.src = '/img/heavy-img.png'; // preload the img
var myImg = document.getElementById('my-img'); // get the element with id="my-img" out of the DOM
// create a mouseover event
myImg.onmouseover = function() {
setTimeout(function() {
this.src = '/img/heavy-img.png' // load the img
}, 1000); // a delay of 1000ms = 1s
};
</script>

Categories