Vuejs - Check if image url is valid or broken - javascript

It's exactly same as Angular 2 - Check if image url is valid or broken.
how can I implement this in vuejs?

Vue.js has an #error event that you can hook into. From vuejs issue#3261. So you could do:
<template>
<img :src="avatarUrl" #error="imageLoadError" />
</template>
<script>
export default {
methods: {
imageLoadError () {
console.log('Image failed to load');
}
}
};
</script>
Edit: I've discovered this also works for <audio> tags (and I suspect other elements which define a src attribute and load an asset)!
Edit2: Silly me! It's actually an interface for adding a listener to the native onerror event that many HTML elements emit, similar to <input #blur="someHandler">, etc.

It seems that #error works fine. I personally used a method with an event in order to set an alternative image.
<img :src="imageUrl" #error="imageUrlAlt">
The method:
imageUrlAlt(event) {
event.target.src = "alt-image.jpg"
}
From Vue.js issue#5404.
Optimal solution:
<img :src="imageUrl" #error="imageUrl='alt-image.jpg'">
Thanks everyone for your valuable comments.

I use a computed property that returns a string with the placeholder URL instead of #error handler like this. This way if source is null or undefined the placeholder will be loaded.
<img :src="source || computedPropertyString" />

Related

image tag - how to put on an ICON (not string - NOT URL) in case of url failure?

I am using React.js as Frontend framework,
I have an icon from antd, and I want to put it in the 'alt' prop of an image tag,
so in case that the url I pass there will be null - it will go to put the icon there.
I tried using 'alt' but it only accepts string.
is it possible to put there an icon? (like one from antd?)
to emphasize - I want to add it as -
<Image alt={<StepBackwardOutlined />}
as in in an actual icon and NOT AS A URL.
You can use on onError.
Inside onError you can create a function outside the main return for ex:-
const onErrorImage = ((e) => {
e.target.src = <StepBackwardOutlined />
})
<img onError={onErrorImage} />
I never tried it with a component....and i never saw someone using it....so i am not sure that it will work or not.
Use the onerror attribute.
From the docs:
<img src="imagefound.gif" onerror="this.onerror=null;this.src='logoIcon.jpg';" />
Here logoIcon.jpg is the icon path.

How to pass an alt attribute in an on click method

Hello I have the following code:
<img alt="image321" onclick="image(//here i want to pass the alt attribute to my function Bild()//);" src="http://i3.ytimg.com/vi/${videoId}/hqdefault.jpg" />
<script>
function image(alt){
alert(alt.src);
}
</script>
I have my image and have given it an alt attribute with the value "image321".Now I want to pass this value to my function image() and output the value with alert as soon as I clicked on the image. But the output is always undifined. Could someone please help me how to solve this problem.
Many greetings Nils
First thing would be to avoid inline handlers - they have quite a few problems, too many to be worth using nowadays, such as a demented scope chain and quote escaping issues. Attach event listeners properly using Javascript with addEventListener instead.
Inside the listener, reference this to get to the clicked element, and its src property to get to its src:
document.querySelector('img').addEventListener('click', function() {
console.log(this.src);
console.log(this.alt);
});
<img alt="image321" src="http://i3.ytimg.com/vi/${videoId}/hqdefault.jpg" />
function myfunc(img){
alert(img.alt);
}
<img alt="image321" onclick="myfunc(this);" src="http://i3.ytimg.com/vi/${videoId}/hqdefault.jpg" />
You should try using this, which sends the element that you run the function with.
Here is an example:
function image(alt) {
alert(alt.src);
}
<img alt="image321" src="http://i3.ytimg.com/vi/${videoId}/hqdefault.jpg" onclick="image(this)"/>

Jquery replaceWith keep onclick

How can I keep onclick="" value with JQuery replaceWith ? I'm making a assets system that preload every image and put it on a Javascript image() object, and using a special data attribute for img urls
<img data-assets="images/test.png" onclick="alert('test')">
turn into : (using jquery replaceWith)
<img src="assets/images/test.png">
What I want:
<img src="assets/images/test.png" onclick="alert('test')">
My code:
$("[data-assets]").each(function() {
$(this).replaceWith(Game.Preloading.Assets.Images[$(this).data('assets')]);
});
How can I fix that ? Thanks
While iterating over each [data-assets] element, you could set the corresponding onclick attribute before replacing the element:
$("[data-assets]").each(function() {
var $newImg = $(Game.Preloading.Assets.Images[$(this).data('assets')]);
$newImg.attr('onclick', $(this).attr('onclick'));
$(this).replaceWith($newImg);
});
However, it would be better to just add a src attribute on the existing element rather than replacing it:
$("[data-assets]").each(function() {
this.src = $(Game.Preloading.Assets.Images[$(this).data('assets')]).attr('src');
});
Ideally, you should be using unobtrusive JavaScript and avoiding the inline JavaScript event listeners, but both of the above snippets should work.
I think you would be better off to simple query for your attribute, then use the each method to update the SRC attribute on each matched element.
Im on my phone so a more detailed answer is difficult...
But here goes
$("[data-assets]").each(function(){ $(this).attr("src", Game.Preloading.Assets.Images[$(this).data('assets')]); });

document.getElementById('').src == ??? (is equal to FAIL)

My javascript is
function changeImage(imgID) {
var baseurl = "media/images/";
if (document.getElementById(imgID).src == baseurl+"selection-off.png") {
alert('Success');
document.getElementById(imgID).src = baseurl+"selection-no.png"; }
else {
alert('Fail'); } }
and my HTML is
<div id="mustard" class="checkbox"><img id="mustard-img" class="no-off" src="media/images/selection-off.png" alt="checkbox" onClick="changeImage('mustard-img')" /></div>
I always get Fail when clicking the image. I must be missing something really elementary.
Some browsers convert the img src to the full url (including http://www....)
try alerting it to make sure..
You could use the
document.getElementById(imgID).src.indexOf( baseurl+"selection-off.png" ) >= 0
which checks if one string is contained in the other..
Alert string document.getElementById(imgID).src. It might be taking complete path i.e. including host name while the string you are comparing with has relative path.
I tried your code on my own server.
Result:
document.getElementById(mustard-img).src is
'http://localhost/webfiles/media/images/selection-off.png'
baseurl+"selection-off.png" is 'media/images/selection-off.png'
baseurl seems to show the relative url only.
So that is the reason why "Fail" gets alerted.
Try with the following code:
<div id="mustard" class="checkbox"><img id="mustard-img" class="no-off" src="media/images/selection-off.png" alt="checkbox" onClick="changeImage(this)" /></div>
<script>
function changeImage(img) {
if (img.src.indexOf('selection-off.png')) {
alert('Success');
img.src.replace(/selection-off.png/, 'selection-no.png');
}else{
alert('Fail');
}
}
</script>
The differences with your code:
passing the img reference: this instead of the id in the onclick function
use indexOf instead of ==, for relative paths
Are you sure the DOM is built when the script is loaded ?
It's because the src attribute is changed by the browser. Don't do it that way, the proper way to check and change the css class or style attribute instead.
Image-based checkboxes are quite common, but here is the full solution.
1) Render actual checkboxes first. These work for 100% of browsers.
2) When the page loads, place your "image checkbox" next to the checkbox and hide the checkbox
3) When the image is clicked, toggle the checkbox and use the hidden checkbox to ascertain the state of the image.
When the form is POST-ed, the checkboxes will act like normal checkboxes. If JavaScript is disabled or otherwise not available the form is still usable.

Javascript getElementById()

I'm trying to create a generic javascript function that would change attributes on events.
The way it would work is
function fooFunction(sourceElement)
{
var newName = sourceElement+'Span';
var newElement = document.getElementById(newName);
//Important line
newElement.property = "enter properties here";
}
and I'd call it with something like
<img src="foo.gif" id="foo" name="foo" onmouseover="fooFunction(this.id);"/>
<span id="fooSpan" name="fooSpan">some text here</span>
So in theory, when hovering the image, it should change whatever propery I need to change on the fooSpan object. It works in Opera, but on IE it returns a null object.
Any ideas ?
The idea would be that I would have multiple images that would automatically trigger the property change on the associated text span (typically the css style).
Are you sure you're getting the ID properly in IE? Maybe the ID being passed in is null in IE (perhaps this.id isn't working?).
Try calling it like this:
<img src="foo.gif" id="foo" name="foo" onmouseover="fooFunction('foo');"/>
and see if that helps. I don't see any reason why getElementById() would fail, so the only thing I can think of is that it's an ID issue.
May be this line won't work in IE. "newElement.property"
I don't know the exact reason.
You can use this instead of that line
newElement.setAttribute(property,"enter properties here");
In the mean time, i am trying to find out the reason behind the error.
My suggestion would to do something like this.
function fooFunction(sourceElement,property,propertyValue) {
var newElement = document.getElementById(sourceElement);
newElement.setAttribute(property,propertyValue);
};
And your HTML would look like:
<img src="foo.gif" id="foo" name="foo"
onmouseover="fooFunction('fooSpan','class','mouseover_span');"/>
<span id="fooSpan" name="fooSpan">some text here</span>
I'd STRONGLY urge you to consider using jQuery's built-in attr() method which integrates the function you want perfectly across browsers and is incredibly easy to use.
Using your example, if you wanted to change the "src" property for "foo", you could do it in a single line of code:
$("#foo").attr("src","images/whatever.png");
Similarly, if you wanted to change the html WITHIN "fooSpan", all you'd have to do is:
$("#fooSpan").html("something else");
You can even tie these to events that are going to give you a lot more flexibility than the onmouseover property:
$(document).ready(function(){
$("#foo").mouseover(function(){
$("#fooSpan").html("something else");
$("#foo").attr("src","images/whatever.png");
});
});

Categories