Specific URL's on Window.Onload - javascript

i'm fairly newbie in JS, just learning so don't bash me hard if i say something unorthodox.
Aim
Load specific background image when user enters specific topic on forum
What I've tried
I searched some options and found Window.Onload option that would allow me to load image on background after page loading is complete. The question is how do i trigger specific images on specific topics?
Pseudo Code
if (user enters) /t/sueper-topic
load - super-background.png
else - carry on

var pathImages = {
'/t/sueper-topic': 'super-background.png'
};
window.addEventListener('load', function(){
var src = pathImages[location.pathname];
if(src)
document.body.style.backgroundImage = 'url(' + src + ')';
});

Related

How to call function after the background image loads using pure javascript? [duplicate]

This question already has answers here:
How can I check if a background image is loaded?
(10 answers)
Closed 7 years ago.
I'm new in javascript and php.
My body page has a link of a background image.
I have a div (div.loader) and in my js code, I have a variable var countdown = 15.When my countdown is 0, it will add a class loaded to my div but I don't know how long the image will load and also the images load so slow (for me).
So I want to call a function that will add a class loaded if the image loaded completely. (here's the link of my website loader: acromix.net16.net)
How do I call a function after the background image loads using javascript or php?
(no extensions or plugins)
(This might be a duplicate but this link (jquery,plugins) is not answering my question)
You can do something like this in pure javasciprt.
var backgroundImageUrl = "backgorundImageName.jpg";
// checking if image is already there in cache
if (sessionStorage.getItem(backgroundImageUrl)) {
document.body.style.backgroundImage = "url('" + backgroundImageUrl + "')";
} else {
var img = new Image();
img.src = backgroundImageUrl;
img.onload = function() {
document.body.style.backgroundImage = "url('" + backgroundImageUrl + "')";
sessionStorage.setItem(backgroundImageUrl, true);
img = undefined;
};
}
I have used sessionStorage to track if the image is already in the cache or not. onload won't fire if image is already present in the cache.
If you are talking about javascript then you can use the onload() event function in the body tag of html.
Javascript method:
<script>
function callFunc()
{
//call your another function here
}
</script>
<body onload="callFunc()">
</body>
And if you are thinking to use jquery then call that function in
$(function(){
//your function to be called
})
I hope this helps you.
Have you tried attaching eventListener or onload event to your image object and then perform whatever you are trying to do?
object.addEventListener("load", myScript);
OR
object.onload=function(){myScript};
You should create image objects in javascript and define their src. and then use the event to do whatever you are trying to do .
Here is one example
var imageName = new Image();
imageName.src = "imageName.jpg";
imageName.onload = function()
{
//do your work here
};

Detect multiple images load event

I'm wondering if there is a way to detect load event of multiple images (particularly, a function should execute when the last image in a given set has completed loading).
For instance, an user clicks on a link and lighbox appears with 10 images. When all images have loaded, loading bar should disappear.
jQuery(".lightbox-image").each(function(){
var image = jQuery(this);
jQuery('<img />').attr('src', image.attr('src')).load(function(){
hideLoadingBar();
});
});
This unfortunately triggers hideLoadingBar(); too early (after one image has completed loading).
P.S.
I also need my function to work after images have been cached so: jQuery('#img1, #img2').load(); won't work.
Check out this jQuery imagesLoaded plugin, it should suit your needs I think.
Well, it seems that no one has better idea, so below is my solution/workaround. The other answer to this question is probably what you want to use because it's a library created specifically for that but here's the solution that I'm going to use because it's shorter and simple:
var allImages = jQuery(".lightbox-image").length;
var counter = 0;
jQuery(".lightbox-image").each(function(){
var image = jQuery(this).find('.myimage');
jQuery('<img />').attr('src', image.attr('src')).load(function(){
counter++;
if(counter >= allImages){
hideLoadingBar();
}
});
});
Works for cached images and not cached images.

How can I let users customize background images?

Many sites these days have 'theming' functionality, when user is able to customize the pages' look. Sometimes it's only a fixed set of themes, but sometimes people are free to choose any style they want - for example, they can set up any color of the pages' background.
I want to go a step further - and let them choose the background image as well. The flow is very simple: user uploads a file (via <input type="file" />), then this file becomes a background image - but only for this user.
I can't find anything about this functionality online, though, and I have no clue about what to do.
Something else I was thinking was that, if a user selects a background, maybe I could use HTML5 localstorage to make that background come up every-time that visitor visits the page.
Here's a proof of concept (mostly based on the code given at MDN FileReader doc page + this answer):
HTML:
<input id="test" type="file" onchange="loadImageFile(this)" />
JS: no wrap (head) mode
$(switchBackground);
var oFReader = new FileReader(),
rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
oFReader.onload = function(oFREvent) {
localStorage.setItem('b', oFREvent.target.result);
switchBackground();
};
function switchBackground() {
var backgroundImage = localStorage.getItem('b');
if (backgroundImage) {
$('body').css('background-image', 'url(' + backgroundImage + ')');
}
}
function loadImageFile(testEl) {
if (! testEl.files.length) { return; }
var oFile = testEl.files[0];
if (!rFilter.test(oFile.type)) { alert("You must select a valid image file!"); return; }
oFReader.readAsDataURL(oFile);
}
And here's a working demo, checked in latest Firefox and Chrome versions. Looks to work OK, at least. )
here's a quick solution to this problem.
custom-background.js is a lightweight jQuery plugin to allow users change the website’s default background and saves the background selected to local storage. This plugin can easily be added to any website or web app without any compromise on website's performance.
you can download it from here and check the code
https://github.com/CybrSys/custom-background.js

How can I get the current src of jquery-based iviewer?

I'm currently using the jquery-based iviewer for an online image gallery. This is the code being used to call the initial iviewer source image (edited for brevity):
var $ = jQuery;
$(document).ready(function(){
var iv1 = $(".viewer").iviewer({
src: "/folder/001.jpg",
});
After asking another question elsewhere on SO, I'm currently using this method to drive next/previous buttons by adding '1' to the current image src on click (all images are named incrementally using three digits - 001.jpg, 002.jpg and so on):
var i = 1;
$("#next").click(function()
{
i++;
iv1.iviewer('loadImage', "/folder/" + ("00" + i).slice(-3) + ".jpg");
return false;
});
However, the problem is that elsewhere on the same page I'm using some jquery code to change the displayed image in the iviewer on the basis of the class attribute of the relevant links (which are numbered similarly to the images - chimg001, chimg002 and so on):
$("ul.imageThumbs > li > a").click(function()
{
var k = $(this).attr("class");
iv1.iviewer('loadImage', "/folder/" + ((k).slice(-3)) + ".jpg");
return false;
});
(I'm new to both jquery and javascript so I'm happy to hear any suggested mods to the above.)
After using the above code to display new images, the next and previous buttons don't change relative to the newly-displayed image, but only according to the last image accessed via the next/previous buttons.
I'd like to be able to have the next and previous buttons working by first finding the current src of the iviewer and then add one to that, rather than the current method. Can this be done?
From reading the documentation for the plugin at the link you provided, there are a few parts that may be useful.
info(prop, dropRotation) - get some info about the image. Valid values for prop are: display_width, display_height - current physical dimensions of the image; orig_width, orig_height - dimensions of the original image; angle - current rotation angle; zoom - current zoom value in %; src - url of current image;
All the methods should be called through jquery ui notation: $('#viewer').iviewer('method', 'arg1', 'arg2')
So, try something like this:
$('.iviewer').iviewer('info','src');

how to preload large size image?

i have certain links, on mouse over of those links I am changing <div> background image
jQuery I have used is-
function imgchange()
{
$('.smenu li').mouseover( function(){
var src = $(this).find('a').attr('href');
$('.hbg').css('background-image', 'url(' + src + ')');
$(this).find('hbg').attr('title', 'my tootip info');
});
}
It is working fine but the problem is when I running it on server images takes 3-4 sec to be changed on change, but the second time I do mouse over images are getting changed instantly, I think this is because of browser stored images in cache. So I added one javascript to preload images on page onLoad() ivent -
<script language = "JavaScript">
function preloader()
{
heavyImage = new Image();
heavyImage.src = "images/soluinfo1.jpg";
heavyImage.src = "images/soluinfo2.jpg";
heavyImage.src = "images/soluinfo3.jpg";
heavyImage.src = "images/soluinfo4.jpg";
heavyImage.src = "images/soluinfo5.jpg";
heavyImage.src = "images/soluinfo6.jpg";
heavyImage.src = "images/soluinfo7.jpg";
}
</script>
<body onLoad="javascript:preloader()">
but this script has not solved my problem.what should I do?
#Richard's answer (sprites) is probably the best one for what you are after, but the reason your code is not working is that in most browsers, only the last heavyImage.src="" is given enough time to actually register with the browser as an actual request. You're creating only one Image object setting and resetting the .src attribute faster than the browser can request the files (I think modern JavaScript engines take the added step of removing all the intermediate .src statements specifically because of this).
There are a couple of ways to fix this. The easiest is to create multiple Image objects, one for each image. And the easiest way to do that is through something like this:
<script type="text/javascript">
function preloader()
{
function doPreload(strImagePath)
{
var heavyImage = new Image();
heavyImage.src = strImagePath;
}
var arrImages = ["images/soluinfo1.jpg","images/soluinfo2.jpg","images/soluinfo3.jpg","images/soluinfo4.jpg","images/soluinfo5.jpg","images/soluinfo6.jpg","images/soluinfo7.jpg"];
for (var i = 0; i < arrImages.length; i++) {
doPreload(arrImages[i]);
}
}
</script>
By putting the heavyImage variable inside its own function (remember to use the var keyword), you're ensuring that the Image object exists inside its own dedicated scope.
Another way to do this is to attach a "load" event listener to a single heavyImage. Every time the image finishes loading, go fetch the next image. The disadvantage to this method is that your images will be loaded one at a time (bad for navigation images, but great for, say, and image gallery), whereas the first technique will fetch the images in parallel (typicallly four at a time).
You might find it easier to change your approach and use CSS sprites (and another article). Then you would just have one image referenced, and you use CSS to set which part of that image gets shown in which scenario.
This assumes that the images you're using are under your control and you can use an image editor to combine them into one large image.

Categories