cancel an existing image on click event using jquery - javascript

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

Related

Check if jQuery clicked element an anchor containing an img

How can I check if the clicked element was an anchor containing an img?
So for example I want to check if this element was clicked:
<a href="#">
<img src="#" />
<a/>
jQuery(document).click(function(e) {
// e.target.hereIsWhereINeedHelp;
});
Thanks in advance!
If you wish to capture the "click" from any element:
jQuery(document).click(function(e) {
if (jQuery(e.target).is('a') && jQuery(e.target).has('img')) {
// code goes here
}
});
Whether you choose to prevent the "default behavior" is another question.
You can use .is("a") and .has("img"):
<a href="#">
<img src="#" />
<a/>
<script>
jQuery(document).click(function(e) {
var target = $( e.target );
if ( target.is( "a" ) && target.has("img") ) {
//Do what you want to do
}
});
</script>
You can use the has() method to check if an element contains another:
$('a').click(function(e) {
e.preventDefault(); // this will stop the link from going anywhere.
if ($(this).has('img')) {
// do something
}
});
You could also use if ($(this).find('img').length).
Use has() method
this.has("img");
You can use has() or find()
$("a").on("click", function(e) {
e.preventDefault(); // Prevents the link redirection
if ( $(this).has("img") ) {
console.log("has image");
}
});
Just check if the clicked element is an anchor tag using is, and then use find to look for an image. If both are true then you //do something.
jQuery(document).click(function() {
var el = $(this);
if(el.is("a") && el.find("img").length > 0){
//do something
}
});

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

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

html div onclick event

I have one html div on my jsp page, on that i have put one anchor tag, please find code below for that,
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint"
onclick="markActiveLink(this);">ABC</a>
</h2>
</div>
js code
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
here I when I click on div I got alert with 123 message, its fine but when I click on ABC I want message I want to call markActiveLink method.
JSFiddle
what is wrong with my code? please help me out.
The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".
In fact, there are multiple solutions:
Checking in the DIV click event handler whether the actual target element was the anchor
→ jsFiddle
$('.expandable-panel-heading').click(function (evt) {
if (evt.target.tagName != "A") {
alert('123');
}
// Also possible if conditions:
// - evt.target.id != "ancherComplaint"
// - !$(evt.target).is("#ancherComplaint")
});
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
Stopping the event propagation from the anchor click listener
→ jsFiddle
$("#ancherComplaint").click(function (evt) {
evt.stopPropagation();
alert($(this).attr("id"));
});
As you may have noticed, I have removed the following selector part from my examples:
:not(#ancherComplaint)
This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.
I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.
Try this
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').click(function (event) {
alert($(this).attr("id"));
event.stopPropagation()
})
DEMO
Try following :
$('.expandable-panel-heading').click(function (e) {
if(e.target.nodeName == 'A'){
markActiveLink(e.target)
return;
}else{
alert('123');
}
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
Here is the working demo : http://jsfiddle.net/JVrNc/4/
Change your jQuery code with this. It will alert the id of the a.
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
markActiveLink();
alert('123');
});
function markActiveLink(el) {
var el = $('a').attr("id")
alert(el);
}
Demo
You need to read up on event bubbling and for sure remove inline event handling if you have jQuery anyway
Test the click on the div and examine the target
Live Demo
$(".expandable-panel-heading").on("click",function (e) {
if (e.target.id =="ancherComplaint") { // or test the tag
e.preventDefault(); // or e.stopPropagation()
markActiveLink(e.target);
}
else alert('123');
});
function markActiveLink(el) {
alert(el.id);
}
I would have used stopPropagation like this:
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').on('click',function(e){
e.stopPropagation();
alert('hiiiiiiiiii');
});
Try out this example, the onclick is still called from your HTML, and event bubbling is stopped.
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint" onclick="markActiveLink(this);event.stopPropagation();">ABC</a>
</h2>
</div>
http://jsfiddle.net/NXML7/1/
put your jquery function inside ready function for call click event:
$(document).ready(function() {
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
});
when click on div alert key
$(document).delegate(".searchbtn", "click", function() {
var key=$.trim($('#txtkey').val());
alert(key);
});

Categories

Resources