How to detect when -webkit-mask-box-image has downloaded - javascript

I generate an mask image on a web server programmatically, then apply it to a HTML element with the following code:
imageToMask.style["-webkit-mask-box-image"] = "url('" + featherURL +"') 100 stretch";
How can I find out when the image comes back and has finished downloading, so that it doesn't just pop onto the page?

You can probably do something similar to what #lonesomeday did in:
jQuery .on() not bound when script inserted into the DOM
Something along these lines:
$('button').click(function() {
var imageToMask = document.createElement('img');
imageToMask.style["-webkit-mask-box-image"] = "url('" + featherURL +"') 100 stretch";
imageToMask.onload = function() {
//Custom behaviour
};
document.body.appendChild(imageToMask);
});

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
};

Event on image load - custom image from user defined url / input - load() doesn't work

I want to achieve a simple event (html change in span) when image from custom / user defined url gets loaded.
http://jsfiddle.net/n2m8u5xb/3/
$('#btn').click(function(){
$(this).html('loading...'); //works
$('#img').css("backgroundImage", "url('"+$("#img-url").html()+"')");
$('#img-url').html(url('"+$("#img-url").html()+"'));
});
$('#img').load(function(){
$('#btn').html('Go'); //doesn't work
});
This load() function doesn't work. I also tried with if else in the click function.
So how in this case to detect custom image load and how to trigger the event?
here are some random large images for quick testing (smallest - largest):
http://i.imgur.com/tJVDlKz.jpg
http://i.imgur.com/NZllSc0.jpg
http://photojournal.jpl.nasa.gov/jpeg/PIA13932.jpg
You can either use an "img" tag for this, or if you insist on using background-image, you can first load it via javascript and then place it as css
something like this:
$('#btn').click(function(){
$(this).html('loading...');
var img = new Image(),
url = $("#img-url").html();
img.onload = function () {
$('#img').css("backgroundImage", "url('"+url+"')");
$('#btn').html('Go');
};
img.src = url;
$('#img-url').html("url('"+url+"')");
});

'Overlay transparent image' jQuery breaks when new class is added

I found this script HERE to overlay a transparent image over photos that I would like to 'protect' on my site. On images that have hyperlinks, I would like be able to give them a special class and make them accessible.
Here is the original script:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var pixelSource = 'http://static.squarespace.com/static/51c351f0e4b0c89ff2b61cb8/t/52cc3905e4b0167d33cd524e/1389115653884/Transparent.gif';
var useOnAllImages = true;
// Preload the pixel
var preload = new Image();
preload.src = pixelSource;
$('img').live('mouseenter touchstart', function(e) {
// Only execute if this is not an overlay or skipped
var img = $(this);
if (img.hasClass('protectionOverlay')) return;
if (!useOnAllImages && !img.hasClass('protectMe')) return;
// Get the real image's position, add an overlay
var pos = img.offset();
var overlay = $('<img class="protectionOverlay" src="' + pixelSource + '" width="' + img.width() + '" height="' + img.height() + '" />').css({position: 'absolute', zIndex: 9999999, left: pos.left, top: pos.top}).appendTo('body').bind('mouseleave', function() {
setTimeout(function(){ overlay.remove(); }, 0, $(this));
});
if ('ontouchstart' in window) $(document).one('touchend', function(){ setTimeout(function(){ overlay.remove(); }, 0, overlay); });
});
});
</script>
I was told to change this line:
$('img').live('mouseenter touchstart', function(e) {
To this:
$('img').not('.FreeMe').live('mouseenter touchstart', function(e) {
... and give the images I want to be clickable the class of '.FreeMe'.
When I run the script with no changes, the transparent overlays work great. Once I change that line of code and add the special class, all of the images become accessible again and the script no longer works.
HERE is a link to the page I've been working on. The Photographers information at the bottom of the screen is the image I would like to add a hyperlink to.
I have been searching high and low in order to make this work but was unable to find a solution to the problem. I'm very new to Javascript and jQuery, but know just enough in CSS and HTML to be dangerous.
I appreciate any help you all could provide.
You should use the .on() method instead of .live(), since the .live() method can't be chained like other jQuery methods (the params are just the same).
Quoting jQuery's doc on .live():
Use of the .live() method is no longer recommended since later
versions of jQuery offer better methods that do not have its
drawbacks. In particular, the following issues arise with the use of
.live():
• Chaining methods is not supported. For example, $( "a" ).find(
".offsite, .external" ).live( ... ); is not valid and does not work
as expected.
Plus, as said in the comments, as of jQuery 1.7, the .live() method is deprecated.
You an see a working demo with adorable kittens here.

Specific URL's on Window.Onload

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 + ')';
});

Preload background image

There's tons of articles of how to preload an image, however I can't seem to find anything useful about preloading a background image with jquery.
I made a simple html mockup of what I'd like to achieve:
http://jsfiddle.net/3rfhr/
A loading div appears
Background is loaded
Loading div disappears
Background DIV appear
I can handle the div transitions but I'm clueless as to how I should go about preloading a css background. Thanks for reading my question :)
You can't as long as it's a background image. Load it normally and then set the background image. Something like this:
var $img = $( '<img src="' + src + '">' );
$img.bind( 'load', function(){
$( '.yourDiv' ).css( 'background-image', 'url(' + src + ')' );
} );
if( $img[0].width ){ $img.trigger( 'load' ); }
the last line is needed in some browser in case the image is cached.
To do the preloading, why not grab the URL from the css attribute with jQuery? Something like this:
var bg_url = jQuery("#DIV-THAT-NEEDS-PRELOADING").css('background-image');
// using regex to replace the " url( ... ) "...
// apologies for my noobish regex skills...
bg_url = str.replace(/ /g, '', bg_url); // whitespace...
bg_url = str.replace(/url\(["']?/g, '', bg_url); // next, the 'url("'...
bg_url = str.replace(/["']?\)/g, '', bg_url); // finally, the trailing '")'...
// without regex, using substring if confident about no quotes / whitespace...
bg_url = bg_url.substring(4, bg_url.length-1);
// preloading...
var img = new Image();
img.onload = function()
{
// do transitions here...
};
img.src = bg_url;
Here's a post from last week that covered preloading images with jQuery: HTML 5 File load image as background-image
And here is the solution that post referenced: http://sveinbjorn.org/dataurls_css
You logic is almost good, but you can not catch events for CSS in jquery.
You need to load the background image to some <img> element. Catch the event load of that element and when it's fired you change the background image to that src and do the rest of your logic.
A working example with a mock setTimeout to simulate loading time.
The relevant jQuery code is:
$('#LOADING-SIGN-DIV').fadeOut();
$('#DIV-THAT-NEEDS-PRELOADING').fadeIn();

Categories