.error inside .click function - javascript

I'm doing some testing with working and broken images:
HTML:
<img src="http://asdf.com/working.jpg" />
<img src="http://asdf.com/broken.jpg" /> <!-- non valid URL -->
jQuery:
$('a').click(function() {
$(this).find('img').error(function() {
alert('Image does not exist!');
});
return false;
});
This works to an extent... Basically I want it to alert ONLY if the user clicks on the broken image. What am I doing wrong?

I would bind to the image for error events, then add the alert logic if there was an error.
Here's a working JSFiddle example I created.
$( "img" ).error(function() {
$( this ).click(function() {
alert('Image does not exist!');
});
});

The error() method was deprecated in jQuery 1.8. So you should be using on('error',function(){}); instead. But, you still have the issue where the error handler has to be attached before the image load is attempted. So, you can set the img src after you attach the handler.
EDIT: It was bothering me that I didn't have a src in my img tag (invalid HTML), so I found this inspired stack overflow: What's the valid way to include an image with no src?. The src="//:0" is from there.
HTML:
<img data-src="http://placekitten.com/300/300" src="//:0" />
<img data-src="http://asdf.com/broken.jpg" src="//:0" />
<!-- non valid URL -->
Javascript
$(document).ready(function () {
$('img').on ('error', function () {
$(this).data('error',true);
}).each(function() {
$(this).attr('src',$(this).data('src'));
});
$('a').click(function () {
if($(this).find('img').data('error') == true) alert('Image does not exist!');
return false;
});
});
http://jsfiddle.net/10xjo3of/2/

You could use onerror attribute for images. the following compatibility table lists the browsers that support the onerror attribute and you can see that you can use this without any issue:
http://www.quirksmode.org/dom/events/error.html
Add onerror="$(this).addClass('error');" to images like this:
<img src="http://asdf.com/working.jpg" onerror="$(this).addClass('error');" />
<img src="http://asdf.com/broken.jpg" onerror="$(this).addClass('error');" /> <!-- non valid URL -->
And on every click, check the error class:
$('a').click(function() {
if ($(this).find('img').hasClass('error')){
alert('Image does not exist!');
}
});
JSFiddle Demo

Related

stopPropagation() not working

I want to stop bubbling when click on image. I cannot set javascript void on href as it is required. I have used stopPropagation but it is not working.
function showurl(e){
e.stopPropagation()
window.location="http://www.yahoo.co.in"
}
<a href="http://www.google.com">
<img src="http://media.expedia.com/media/content/shared/images/navigation/expedia.co.in.png" onclick="showurl(event)" />
</a>
As this was a jQuery question I would suggest never using onclick attributes. They only support a single handler and they are are "ugly" (read: harder to find and maintain) :)
$('img").onclick = function(e) {
e.preventDefault();
window.location="http://www.yahoo.co.in";
}
or
$('img").onclick = function() {
window.location="http://www.yahoo.co.in";
// return false here does the same as e.stopPropagation() and e.preventDefault();
return false;
}
As this handler applies to all img elements, you may want to data-drive the whole thing (using attributes) like this:
Put the target url in the image as a data-url attribute
<a href="http://www.google.com">
<img src="http://media.expedia.com/media/content/shared/images/navigation/expedia.co.in.png"
data-url="http://www.yahoo.co.in" />
</a>
And code-wise:
$('img").onclick = function(e) {
// See if image has a data-url attribute
var url = $(this).data('url');
if (url){
window.location=url;
// only prevent default if it was an image with a link attribute
e.preventDefault();
}
}
I would suggest binding it from JS, even with a basic onclick then use return false; or use preventDefault. (demo)
document.getElementsByTagName("img")[0].onclick = function() {
window.location="http://www.yahoo.co.in";
return false;
}
HTML
<a href="http://www.google.com">
<img src="http://media.expedia.com/media/content/shared/images/navigation/expedia.co.in.png" />
</a>

JS image source attribute to trigger action

I am in a (steep) learning cuve with JS. I would suppose my JS code will only trigger action for image with src attribute : "http://placehold.it/350x150" to change to the targeted new link (320x120) on click. but it changes ALL images to the latest, any idea plz ?
Complete code: http://jsfiddle.net/celiostat/nmH8L/34/
HTML:
<img class=icon1 src="http://placehold.it/350x150"/>
<img class=icon2 src="http://placehold.it/140x140"/>
<img class=icon3 src="http://placehold.it/200x100"/>
<img class=icon4 src="http://placehold.it/350x65"/>
JS:
$(document).ready(function() {
$('.icon3').on("click", function() {
if($('img').attr('src') === 'http://placehold.it/350x150')
$('img').attr('src', 'http://placehold.it/300x120');
})
})
If you want to resume back the former image to it's initial state, then for each click event you should do the following.
$('.icon1').on("click", function (e) {
if ($(e.currentTarget).attr('src') === 'http://placehold.it/350x150') {
var changedImage = $('[data-image-name="changed_image"]')
changedImage.removeAttr('data-image-name').attr('src', changedImage.attr('prevSrc'));
$(e.currentTarget).attr('data-image-name', 'changed_image');
$(e.currentTarget).attr('prevSrc', 'http://placehold.it/350x150');
$(e.currentTarget).attr('src', 'http://placehold.it/300x150');
}
})
$('img') selects all image elements. Use $(this) to get the element the event fired on.
Change your code to
$(document).ready(function() {
$('image').on("click", function() {
if($('img').attr('src') === 'http://placehold.it/350x150')
$(this).attr('src', 'http://placehold.it/300x120');
})
})

Issue using added class with jQuery

I wrote an inline script to automatically handle when a browser can not load an SVG and replace it with a PNG image. This part works great, however I also want to change the image onhover and this answer worked great for me except that I don't need it to "run and find" if the browser can handle SVG and doesn't use the PNGs. So, I thought I would have it trigger when a class of noSVG (herein referred to as "myclass") was added to the IMG tags.
Now here's were the issues start, I can use CSS to modify the style of the class which is added. But I can't use jQuery to modify it. Even stranger, when I went to add it to JSFiddle for you guys, it works. Before you guys think that I'm using a bad version of jQuery I tested multiple versions (including 1.10.1 which is use by JSFiddle).
HTML:
<img src="1.svg" onerror="this.onerror=null; this.src='1.png'; this.className+=' myclass';" class="image" id="1" />
jQuery:
$(function() {
$(".myclass")
.mouseover(function() {
var src = $(this).attr("src").match(/[^\.]+/) + "hover.png";
$(this).attr("src", src);
//console.log("moused over");
})
.mouseout(function() {
var src = $(this).attr("src").replace("hover.png", ".png");
$(this).attr("src", src);
//console.log("moused out");
});
});
JSFiddle
You are adding the class myclass dynamically to the image, so you need to use event delegation
$(function () {
$(document).on('mouseover', ".myclass", function () {
var src = $(this).attr("src").replace('.png', 'hover.png');
$(this).attr("src", src);
//console.log("moused over");
}).on('mouseout', ".myclass", function () {
var src = $(this).attr("src").replace("hover.png", ".png");
$(this).attr("src", src);
//console.log("moused out");
});
});
Demo: Fiddle

cancel an existing image on click event using jquery

In the actual website, when clicking on an image from thumbnails, it opens a slideshow.
I have created a new onclick event:
$('.thumbnails a').click(function(event) {
//my piece of code
});
How can I cancel the existing on click event, not knowing which selector's been used to trigger the event (parent? child? specific class?)
I have tried things like:
event.stopPropagation()
$(this).stop()
with no success.
RE-EDIT--------------------------------------------------------
html starts with:
<div class="images">
<a title="Voyage itinérant en Boutre" rel="prettyPhoto[product-gallery]" class="zoom" href="http://dev.snorkeling-voyages.com/wp-content/uploads/2013/05/snorkeling-madagascar-001_alefa.jpg" itemprop="image">
<img width="462" height="392" class="yit-image attachment-shop_single" src="http://dev.snorkeling-voyages.com/wp-content/uploads/2013/05/snorkeling-madagascar-001_alefa-462x392.jpg">
</a>
<div class="thumbnails nomagnifier">
<a class="zoom first" rel="prettyPhoto[product-gallery]" title="bateau itinerant madagascar" href="http://dev.snorkeling-voyages.com/wp-content/uploads/2013/05/snorkeling-madagascar-002_alefa.jpg">
<img width="100" height="80" class="yit-image attachment-shop_thumbnail" src="http://dev.snorkeling-voyages.com/wp-content/uploads/2013/05/snorkeling-madagascar-002_alefa-100x80.jpg"></a>
jQuery to change the featured image on thumbnails click:
$('.thumbnails a').click(function(event) {
var destination= $('.images >a');
destination.empty();
$(this).prependTo(".images >a");
$('.images a a img').attr('width','470');
$('.images a a img').attr('height','392');
//replace src string
var src=($('.images img').attr('src'));
var pattern = /[100x80]/;
if(pattern.test(src))
src=src.replace("100x80", "462x392");
$('.images a a img').attr('src',src);
$('.images a a img').attr('class','yit-image attachment-shop_single');
});
#bfavaretto comment helped me localise an existing a .zoom click event (very useful thanks)
(how can I know the js file? )
I have added a
$('.zoom a').click(function(event) {
return false ;
// or event.preventDefault();
});
and this does not prevent the slider from being opened still!
You can remove all other click handlers from an element with .off:
$('.thumbnails a').off('click');
In case the event was delegated, you need something like this:
$(document).off('click', '.thumbnails a');
However, you have to do that from outside your click handler, or it may be too late.
You can use .preventDefault() to prevent the link from executing:
event.preventDefault();
jsFiddle here
You can try using either of the two commented statements:
$('a').click(function(e){
//e.preventDefault();
//return false;
});
I did something else If I understand correclty what you want please take a look
off
off
off
off
and the javascript:
$('a').click(function(event){
event.preventDefault();
if ($(this).attr('data-status') == 'on') {
$(this).attr('data-status','off');
$(this).html('off');
return;
}
var areOn = 0;
$('a').each(function(){
if ($(this).attr('data-status') == 'on') {
areOn++;
}
})
if (areOn == 0) {
$(this).attr('data-status','on');
$(this).html('on');
}
})
http://jsfiddle.net/ERMtg/9/
You can use return false, I think that will do
$('.thumbnails a').click(function(event) {
return false;
});

Jquery anchor tag display problem

I am unable to show an anchor tag to display itself using .show() in Jquery or javascript. Conn Window is visible by default. It hides and displays the div but it is unable to do the same with anchor. I have manually tried to change it in firebug/IE dev tools and it works there. It just doesn't work when I do it with jquery/javascript.
Here is the HTML code:
<div id="connWindow">Conn Window
<div id="closeButton" onclick="javascript:connHide();"></div>
</div>
Here is the jquery code:
function connHide()
{
$('#connTab').show();
$('#connWindow').hide();
}
function connShow()
{
$('#connWindow').show();
$('#connTab').hide();
}
Any help will be greatly appreciated!
Why not bind your click events in jQuery as well
function connHide()
{
$('#connTab').show();
$('#connWindow').hide();
}
function connShow()
{
$('#connWindow').show();
$('#connTab').hide();
}
$(document).ready(function () {
$("#contab").click(function () {
connShow();
return false;
});
$("#connWindow").click(function() {
connHide();
});
});
The inline CSS display:none is overriding the mechanism jQuery uses to show and hide.
Hide the anchor programmatically instead:
HTML:
<div id="connWindow">
Conn Window
<div id="closeButton"></div>
</div>
Script:
$(function() { // on document load
$('#connTab').css('display', 'none');
// I'm going to replace your inline JS with event handlers here:
$('#connTab').click(function() { connShow(); return false; });
$('#closeButton').click(function() { connHide(); });
});
function connHide() {
$('#connTab').css('display', '');
$('#connWindow').css('display', 'none');
}
function connShow() {
$('#connWindow').css('display', '');
$('#connTab').css('display', 'none');
}
Hope that helps.
You don't need to state javascript: for onclick events. Try changing to:
<div id="closeButton" onclick="connHide();"></div>
I would also change the first line to the following:

Categories

Resources