Reference loaded <img> in javascript - javascript

I use a carousel jQuery plugin which defines a container which must contain <img> tags. The images are loaded and shown, the carousel works.
I am now implementing image preview on hover. I've created a separate <div> for this purpose which is being shown with the loaded image.
The problem is that I'm programatically creating a new <img> tag within the <div> each time the mouse hovers over a different image. This results in massive amount of unnecessary server requests.
How can I use preloaded images from the carousel within the image preview div?
I don't need a fully working solution, I'll accept abstract answers.

Further to the comments, here's a working sample of the cloneNode method I mentioned. I've not bothered with the mechanics of the containers or of triggering the behaviour via a mouse hover, just click the existing image and it will work.
You'll also have to change the image source to something you already have. I'm testing with the full-res version of this image: https://commons.wikimedia.org/wiki/File:SoundingRocketSamplePayload-02.jpg
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('srcImg').addEventListener('click', myTest, false);
}
function myTest()
{
var tgtElem = byId('srcImg');
var clone1 = tgtElem.cloneNode(true);
var clone2 = tgtElem.cloneNode(true);
var clone3 = tgtElem.cloneNode(true);
document.body.appendChild(clone1);
document.body.appendChild(clone2);
document.body.appendChild(clone3);
}
</script>
<style>
</style>
</head>
<body>
<img id='srcImg' style='width: 256px' src='rockets.jpg'/>
</body>
</html>

Related

svg trigger animation issue (svgator)

Can you tell me why this example http://www.silkcutz.co.uk/test/ taken from here https://github.com/SVGator/trigger-animation which uses (logo.svg with ID "e6flsqoxhzzs1") works absolutely fine....
BUT http://www.silkcutz.co.uk/test/2.html (using Untitled.svg with ID "eOKHP9YQpje1") doesnt, this is a very simple animation of a box moving position (just for test purposes).
Both html files are very simple and should require only the filename and ID changing but the examples 2.html... you would think the svg has issues but when testing the SVG file (Untitled.svg) using the upload svg facility on the live demo here https://www.svgator.com/help/getting-started/svgator-player-js-api it work fine and is triggered as expected!
Any help would be very much appreciated!
To use the technique described there, you need to export the SVGator project using "Animation start: On click".
But programmatic animation has been recently implemented. Check these resources:
https://www.svgator.com/help/getting-started/animate-programmatically
https://www.svgator.com/help/getting-started/svgator-player-js-api
Here's a complete example on how to use Player API with a SVG embedded in an tag:
<!DOCTYPE html>
<html>
<head>
<title>Testing SVG</title>
<script>
//Wait for the document to load
document.addEventListener("DOMContentLoaded", function() {
//grab the <object> element
let object1 = document.getElementById('animated-svg');
//Wait for the content of the <object> to load
object1.addEventListener("load", function() {
//grab the <svg> element
let svg = object1.contentDocument.getElementById('e5478wvxh25l1');
//Wait for the SVGtor player to be ready for use
svg.svgatorPlayer.ready(function(player) {
//inset your code here; i.e.
player.play();
});
});
});
</script>
</head>
<body>
<object id="animated-svg" type="image/svg+xml" data="animated.svg" style="height: 857px;"></object>
</body>
</html>
It's also worth knowing that no matter how you set the "Animation start", you always have access to the Player API and can control the animations as a PRO user.

Using JavaScript, how can I replace broken images with any other HTML data

I provide a service, that help users to find location of pictures. My problem is that the pictures are stored on an other internal site, and my users needs to be connected to it to see the pictures (some may not have access, as my service provide other info). The built-in replacement (alt attribute of IMG) doesn't provide enough flexibility to inform the user of the corrective actions
<div id=theDiv>
<img src='http\internalSite\'+this.name+'.jpg'
alt='Please connect to internalSite to see the picture '+this.name+'.jpg'>
</div>
I would like to improve the alt text, at least provide a link to 'internalSite' (or even better, load the connection page in an iFrame perhaps...). I found this to be impossible, so I would use onError attribute of IMG to replace what I have on the div
But in fact, the image is placed here by script, so I think this is a bit silly and clearly not optimized
how can my script detect that the picture is unavailable before, to decide what I do?
in pseudo code:
if (isURLavailble(path)){
loadPicture();
} else {
loadSomethingNiceToSayPicIsntAvailable() ;
}
is it possible to define a working function (and of course cross-browser) that does isURLavailble(path); ?
You could replace all broken images (or a subset of them) with login links:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<img src="doesnotexist">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
// See also https://stackoverflow.com/a/34726863/100754
$( document ).ready( function () {
"use strict";
$('login here').replaceAll($('img').filter( function () {
return !(this.complete && this.naturalHeight !== 0);
}));
});
</script>
</body>
</html>
See also this answer to Check if an image is loaded (no errors) in JavaScript.
Or, you can do something like this if you are setting images after the page has loaded:
var img = new Image();
img.onload = function () {
$(img).appendTo('.image-container');
};
img.onerror = function () {
$('login here').appendTo('.image-container');
};
img.src = 'doesnotexist';
You can check url using JQuery jqXHR calls:
$.get("urlToCheck.com").done(function () {
loadPicture();
}).fail(function () {
loadSomethingNiceToSayPicIsntAvailable() ;
});

How to run code only when iframe loaded

I have been battling with this issue for a few days now and finally found a partial solution but I think it could be improved.
In my project, I have a series of iframes that contain videos. When a link is clicked are displayed with a slide transition and when the link is clicked again the video stops and the span containing the iframe is hidden also with a transition.
This is achieved by adding and removing a css class of "open" that has a height and a transition in it. In addition to this I have an event listener that collapses the containing span also when the video finishes. All this works fine and to save time I am not posting the code.
The issue I was having was with slow page loading times, so I removed the src attribute for the iframes from the html and moved it to my js file and assigned it only after the click is performed. This wasn't working and I realised I needed the iframe to fully load before running the rest of the code inside the "click" method. So I delayed this part of the code by 100ms.
All this works, but I feel it would be better to have the rest of the code run not after a 100ms lapse but when the iframe is loaded (in case page viewed by slower computers). Not sure how to do this.
Here is the code as it stands now:
var player;
var frame = $("#frame");
frame.bind("load", function () {
player = $(this).contents().find("#myVid");
player.on('ended', function () {
frame.removeClass("open");
});
});
$("#clickableLink").click(function(){
if (frame.hasClass("open")) {
frame.removeClass("open");
frame.contents().find('#myVid').get(0).pause();
} else {
function delayed(){
frame.addClass("open");
frame.contents().find('#myVid').get(0).play();
}
frame.attr("src","iframe.html");
setTimeout(delayed, 100);
}
});
Fairly new to development so I am looking for the simplest way to do this. Any help appreciated.
Here is a super simple example of calling code when the iframe has loaded. Check out the onload attribute of the iframe tag:
<head>
<script>
function frameLoaded() {
alert('frame loaded!');
};
</script>
</head>
<body>
<iframe id="frame" src="https://en.wikipedia.org/wiki/HTML_element#Frames" onload="frameLoaded(this)" />
</body>

onload not working in <img> element

I don't understand why this function doesn't fire. I want to declare an image in HTML with a single onload function, which will automatically take care of the image's source and mouseover/out functions.
The HTML looks like this:
<img id="menuBtnNovo" onload="imgButton(this)"/>
and the JS function imgButton looks like this:
function imgButton(e){
window.alert("asdasdad");
e.src="images/def/" + e.Id + ".png";
e.onmouseover= function(){ *change image here*}
e.onmouseout= function(){ *change image back here*}
}
Now, not even the alert pops up, and I don't know why. I tried putting script in <head> and setting src to none src="" in the <img>. I'm using Firefox, but it doesn't work in Edge either.
Question is: how do I fire onload function on an image element?
Also, if you have any idea of your own way of implementing this behaviour of automatically loading certain images (that would actually be buttons/links), feel free to share it. I'm new to JS but not to programming.
As you might see, all images are in "images/def/..." and all images for when the mouse is over the img are in "images/mo/...".
I always try and let browser do image replacements, but if you have to use script, than you can do something like this on DOM ready, or window load event:
$('img[data-regular]').each(function(i) {
var thisImage = $(this);
var regular = thisImage.data('regular');
var hover = thisImage.data('hover');
thisImage.attr('src', regular);
/* Preload image for hover */
$('<img/>')[0].src = hover;
/* Set events */
thisImage.on('mouseenter', function(e) {
thisImage.attr('src', hover);
}).on('mouseleave', function(e) {
thisImage.attr('src', regular);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img data-regular="https://placehold.it/350x150" data-hover="https://placehold.it/450x200" />
Also on JSFiddle.

Need to set 1 span's style to display:block on page load for an image gallery made up of span's set to display:none

i have some javascript in the head of a page that controls an image gallery where the user clicks a thumbnail image and a larger image and some text are revealed in a span. there are 10 of these thumbnails per page and i need to find out how to set the 1st thumbnail's hidden span to "block" on page load.
<script type="text/javascript">
function hideSpan(spanName) {
var obj = document.getElementById(spanName);
obj.style.border="0px";
obj.style.color="#fff";
obj.style.display="none";
obj.style.left="333px";
obj.style.padding="0";
obj.style.position="absolute";
obj.style.top="55px";
obj.style.width="244px";
}
function showSpan(spanName) {
var spanEl, count = 1;
while(spanEl = document.getElementById('link' + count++)){
spanEl.style.display = 'none';
}
var obj = document.getElementById(spanName);
obj.style.display="block";
}
</script>
any help with this is VERY appreciated thank you.
The simple, breezy way is to do this:
<body onload="showSpan('link1');">
The trouble here is that the onload event attached to body that way is executed a little late in the page loading (After all the parts-- including images-- are loaded) so it'll be murder for your dial up users. jQuery implements a much better way:
$(document).ready(function () {
showSpan('link1');
});
If you're not using jQuery, then someone here much wiser than I more than likely knows the correct way to do it using "proper" JavaScript, I don't remember the event name that jQuery uses off the top of my head.

Categories

Resources