JS image source attribute to trigger action - javascript

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

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>

.error inside .click function

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

Button click faking

I'm trying to make my mobile web app appear more responsive. So when you click an icon that's an image i want to use jquery mobile to whilst it's being clicked show a different image (different colour) to make it appear that somethings been done, then when you let go it should change back.
I'm trying the following but it doesn't appear to be firing. Anyone have any tips?
$( document ).ready(function() {
$('.homeAlerts').on( "vmousedown", "a", function() {
console.log("Clicked");
$('#homeAlerts').attr('src','mages/HomeIcons/typeOneClicked_0003_Alerts');
});
$('.homeAlerts').on( "vmouseup", "a", function() {
$('#homeAlerts').attr('src','mages/HomeIcons/typeOne_0003_Alerts.png');
});
});
Markup
<div class="iconL">
<a href="#alerts" class="homeAlerts">
<img id="homeAlerts" src="images/HomeIcons/typeOne_0003_Alerts.png" />
<center class="pullup">Alerts</center>
</a>
</div>
Use the jquery mousedown and mouseup functions instead:
$("img#homeAlerts").mousedown(function(){
$(this).attr("src", "images/HomeIcons/typeOneClicked_0003_Alerts.png")
});
$("img#homeAlerts").mouseup(function(){
$(this).attr("src", "images/HomeIcons/typeOne_0003_Alerts.png")
});
to answer your original question, pretty sure you should be doing:
$('#homeAlerts').on( "vmousedown", "a", function() {
console.log("Clicked");
$(this).attr('src','mages/HomeIcons/typeOneClicked_0003_Alerts');
});
$('#homeAlerts').on( "vmouseup", "a", function() {
$(this).attr('src','mages/HomeIcons/typeOne_0003_Alerts.png');
});
(your selector is trying to select a class, but you have an id on your image)

jquery Trigger delegate event for nth element onload

In my page i have 10 images all are have the same class "select-option"
My html is
<div class="select-option swatch-wrapper selected" data-name="A Very Scary Monster" data-value="a-very-scary-monster">
<a href="#" style="width:120px;height:120px;" title="" class="swatch-anchor">
<img src="image ur1" alt="" class="" width="120" height="120"></a></div>
Similarly i have 10 images.
function init_swatches() {
$('.select-option').delegate('a', 'click', function(event) {
///////////// Some code here
var $the_option = $(this).closest('div.select-option');
});
}
I want to preselect the 3rd image. Thew selected image has the class 'selected', others are not. How do i trigger this for 3rd or 4th element on load. How to manually trigger this delegate event for nth element.
Here i want to trigger this click event
First bind click event on anchor tag
$('.select-option').delegate('a', 'click', function(event) {
///////////// Some code here
var $the_option = $(this).closest('div.select-option');
});
then manuaaly trigger click event of 3rd element like given below
$('.select-option a').eq(2).click()
or
$('.select-option a').eq(2).trigger("click")
you can use jquery's trigger method
function init_swatches() {
$('.select-option').delegate('a', 'click', function(event) {
///////////// Some code here
var $the_option = $(this).closest('div.select-option');
});
$('.select-option a').eq(2).trigger("click");
}
I'm not sure you're wanting to trigger the click event, but rather use the click event to set the selected class. Something like this might be more suitable:
$(document).ready(function() {
$(document).delegate(".select-option", "click", function(e) {
if ($(this).hasClass("selected") == false) {
$(".select-option.selected").removeClass("selected");
$(this).addClass("selected");
}
});
selectNthImage(3);
});
function selectNthImage(n) {
$(".select-option.selected").removeClass("selected");
$(".select-option:nth-child(" + n + ")").addClass("selected");
};
See a jsfiddle here

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

Categories

Resources