I recycled a lot of code from an old JS project I made back in the very beginning of my learning process, and back then I knew nothing about DOM events. Specifically in this case, onload. What I am looking for is someway to only let the website begin to run once all images have loaded, without putting everything into one big onload function, or rewriting all my code. Is there anyway to do this?
<img src="placeholder.png" onload="continue()" width="100" height="100">
<script>
function continue() {
//This is where I am stuck
}
</script>
The simplest solution would be to set the display property of the body to none when the page is loading, and then have continue() make it visible.
CSS:
body {
display: none;
}
JS:
function continue() {
document.body.style.display = "";
}
If the images aren't going to be dynamically added to DOM you can simply just do the followingaIf the images aren't going to be dynamically added to DOM you can simply just do the following
<html>
<body style="display: none;">
<img src="https://via.placeholder.com/100" alt="">
<img src="https://via.placeholder.com/200" alt="">
<img src="https://via.placeholder.com/300" alt="">
<script>
const imageCollection = Array.from(document.getElementsByTagName('img'));
const promisifier = (imageNode) => {
return new Promise((resolve, reject) => {
imageNode.addEventListener("load", () => {
console.log('image loaded', imageNode);
resolve('Loaded')
});
})
}
Promise.all(imageCollection.map(img => promisifier(img))).then((resp)=>{
document.body.style.display = 'block';
console.log('All images completed Loading');
})
</script>
</body>
</html>
If images are going to be dynamically added you could go for Mutation Observer, let me know if thats the case will add that too.
Related
So I'm new to web development (career change) and I'm hitting a roadblock that I can't seem to get past.
I'm trying to write a script that will change the img src in my HTML. When I use inline JavaScript it does what I want and replaces the image:
<img id="book1" src="placeholder" alt="Book1">
<h5 class="title">TITLE by Author Name</h5>
<p>Book description</p>
<div class="center">
<button type="button" class="amz-btn" id="btn1" onclick="showImage()">Buy from Amazon</button>
<script type="text/javascript">
function showImage() {
let image = document.getElementById("book1");
if (image.src.match("placeholder")) {
image.src = "https://storage.googleapis.com/du-prd/books/images/9781538728529.jpg";
} else {
console.log("This is frustrating");
}
}
</script>
But when I transfer it to my external .js file I get a syntax error saying showImage is not defined.
How can I resolve this?
Here is the code as written just in the external file
document.getElementById("btn1").addEventListener("click", showImage)
function showImage() {
let image = document.getElementById("book1");
if (image.src.match("placeholder")) {
image.src = "https://storage.googleapis.com/du-prd/books/images/9781538728529.jpg";
}
else {
console.log("This is frustrating");
}
}
Someone suggested that I use addEventListener rather than onclick in the HTML so I've done that but I'm confident it's in entirely the wrong place and doing the wrong thing
I've tried running the following in the browser console and it runs perfectly but I still can't get it to work from the external file
const img = "https://storage.googleapis.com/du-prd/books/images/9781538728529.jpg";
document.getElementById("btn1").addEventListener("click", showImage);
function showImage() {
document.getElementById("book1").src = img;
}
Issue resolved!
const img = "https://storage.googleapis.com/du-prd/books/images/9781538728529.jpg";
document.getElementById("btn1").addEventListener("click", showImage);
function showImage() {
document.getElementById("book1").src = img;
}
The reason the above wasn't working was because I did something wrong with the window.addEventListener('load', (event) => { // all code here; }); but after removing that the image appears on a button click
I am trying to Exchange the src of an Image tag on a click Event, the Image src is a png file, but if I click on the Image the source shall Change to a give file.
<img src="images/eye.png" alt="Logo"
id="sidebar-collapse img-logo-main-page"
width="80">
And this is the JavaScript, I get the console Output in the console but Nothing changes:
const gifEgg = {
elements: {
logo: $('#img-logo-main-page'),
logoOverlay: $('#sidebar-image-collapse')
},
addGif () {
this.elements.logoOverlay.click(() => {
console.log("clicked");
this.elements.logo.attr('src', '../images/eyes_move.gif');
});
}
};
gifEgg.addGif();
The problem is that you are treating an id like a class. You gave the image an id of sidebar-collapse img-logo-main-page, but are trying to refer to it with #img-logo-main-page. An element can only have one id, but can have many classes. If you gave it a class name of sidebar-collapse img-logo-main-page, you could refer to it with .img-logo-main-page (any one or more of its classes), but an id must be unique and each element can only have one id.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://images.pexels.com/photos/658687/pexels-photo-658687.jpeg?auto=compress&cs=tinysrgb&h=350" alt="Logo"
id="img-logo-main-page"
width="80">
<button id="sidebar-image-collapse">
Change Image Source
</button>
<script>
const gifEgg = {
elements: {
logo: $('#img-logo-main-page'),
logoOverlay: $('#sidebar-image-collapse')
},
addGif () {
this.elements.logoOverlay.click(() => {
console.log("clicked");
this.elements.logo.prop('src', 'http://2.bp.blogspot.com/-3jbHdEj7o2k/Uk6zNIfJkqI/AAAAAAAAB5s/zf7UzbSkp80/s200/zrikh+ajig.gif');
});
}
};
gifEgg.addGif();
</script>
I am working on a site which has a list of products. Each product has a corresponding image. I am binding the image url to the source attribute like below.
<img :src="product.ImageUrl"/>
If the image is not found, I want to show a default image.
I do as below in cshtml razor syntax (for reference only)
onerror='this.onerror = null;this.src = "#Url.Content("~/images/photo-not-available.jpg")";'
How do I achieve the same in Vue?
You can set an onerror handler function with #error in Vue:
<img :src="" #error="aVueFunctionThatChangesTheSrc">
Since in pure js put onerror inline like this
<img :src="ImgUrl" onerror="this.src='http://example.com/default.jpg'"/>
for vue.js we can replace it
<img :src="ImgUrl" #error="$event.target.src='http://example.com/default.jpg'"/>
I found that changing the src in the #error function kicked off a horrible endless loop of updates, causing a flickering screen etc. My solution so far is:
<span v-if="props.column.field === 'avatar'">
<span v-if="props.row.avatar">
<img alt="avatar" class="round-32" :src="`${props.row.avatar}`" #error="(() => props.row.avatar = null)"/>
</span>
<span v-else>
<img alt="avatar" class="round-32" src="../../../assets/images/avatar-2.jpg"/>
</span>
</span>
I have try to using #error but it doesn't work because in my case, the image was not found, so I try this one, and its work.
<img :src="getImgUrl(filename)">
methods: {
getImgUrl(filename){
try{
return require(`#/assets/${filename}`)
}catch(_){
return require(`#/assets/default.png`)
}
},
}
I ended up with a directive to set a fallback image and prevent the loop:
image-src-fallback.js
const setSrc = (evt) => {
const el = evt.currentTarget;
el.setAttribute("src", el.fallback);
el.fallback = "";
el.removeEventListener("error", _listener);
};
const _listener = (evt) => setSrc(evt);
export default {
bind(el, binding) {
el.fallback = binding.value;
el.addEventListener("error", _listener);
},
unbind(el) {
el.removeEventListener("error", _listener);
},
};
Global import
import imageSrcFallback from "./directives/image-src-fallback.js";
Vue.directive("src-fallback", imageSrcFallback);
Use
<img
v-src-fallback="user.avatar_fallback_url"
:src="user.avatar_url"
/>
Sometimes you can create a method, for example in my case some images are not found because clients have not uploaded images, then you can create a method for it: you can return any value as an image or simple '' for any image.
<div class="flex-shrink-0">
<img
class="h-72 w-full object-cover"
:src="showFirstImageGallery(p.project_images)"
/>
</div>
methods: {
showFirstImageGallery(v){
if (v.length > 1) {
return v[1].img_url
} else {
return ''
}
}
},
I'm trying to add a mute/un-mute button to my website. I created a panoramic tour using a program called Panotour by Kolor. Thing is I exported it as HTML but can't seem to find the audio tags or anything. I found the file which contains the audio files, I just need a way to mute the music.
.
Here's what I'v done so far.
<div>
<img class="img-responsive" src="Images/muteon.png" id="mute" onclick="toggleSound(this);">
</div>
<script>
function toggleSound(img)
{
if(img.src.match(/blank/))
{
console.log('black');
img.src = "Images/muteon.png";
}
else
{
console.log('blank');
img.src = "Images/muteoff.png";
}
}
</script>
I'm working on a simple project that includes a media (mp3) player in the sidebar. I can get the play/pause button to visually switch and I can turn off the audio by assigning a href to another image however when trying to get the swapped image to pause audio I just can't seem to figure it out, here's my code..
EDIT: deleted shotty code
EDIT: Figured out three ways to do this, the two kind people below posted great ways but I also figured out how to crudely do this via jquery.
$('#left-05-pause_').click(function(){
$('#left-05-pause_').hide();
$('#left-05-play_').show();
});
$('#left-06-audio_').click(function(){
audio.volume = 1;
$('#left-06-audio_').hide();
$('#left-06-mute_').show();
});
Mitch, I have three points for you:
there's no need to wrap <a> around <img>
for performance avoid overuse of selecting elements (like getElementById), because once you've selected a link to the element put it into a variable and use again to access the same element
use native info about element's state (for <audio> in this example) - explore its properties
All in all just try next sample (file names have been changed for clarity):
<body>
<audio id="audioId">
<source src="song.mp3" type="audio/mp3" />
</audio>
<img id="imageId" src="play.png" onclick="toggle()" />
<script>
var audio = document.getElementById( 'audioId' )
, image = document.getElementById( 'imageId' )
function toggle()
{
if ( audio.paused )
{
image.src = 'pause.png'
audio.play()
}
else
{
image.src = 'play.png'
audio.pause()
}
}
</script>
</body>
You can try this
<a href="#">
<img src="http://royaltrax.com/aadev/images/left/images/left_05.png" id="imgPauseChange" onclick="changeImage()">
</a>
<script language="javascript">
function changeImage() {
if (document.getElementById("imgPauseChange").src == "http://royaltrax.com/aadev/images/left/images/left_05.png")
{
document.getElementById("aud").play();
document.getElementById("imgPauseChange").src = "http://royaltrax.com/aadev/images/left/images/left_05-pause.png";
}
else
{
document.getElementById("aud").pause();
document.getElementById("imgPauseChange").src = "http://royaltrax.com/aadev/images/left/images/left_05.png";
}
}
</script>