Check if jQuery clicked element an anchor containing an img - javascript

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

Related

localStorage onload show my selected div?

how show hide div with localStorage, example if i select IT, onload show div IT.
my js code
itlang = document.getElementById('LangIT');
itlang.onclick = function(event) {
localStorage.setItem('a_avlang', '1');
$('.avlan').hide();
$('.av-it').show();
};
if (a_avlang === '1') {
localStorage.getItem('a_avlang', '1');
$('.avlan').hide();
$('.av-it').show();
} else {
localStorage.setItem('a_avlang', '0');
$('.av-it').hide();
}
}
my buttons html
<a class="avlangbuttons" href="#it" id="LangIT" target="_self">IT</a>
<a class="avlangbuttons" href="#en" id="LangEN" target="_self">EN</a>
My div to Show/hide html
<div class="avlan av-it" style="display:none;">
IT
</div>
<div class="avlan av-en">
EN
</div>
You have some invalid syntax.
localStorage.getItem('a_avlang', '1'); is invalid, there is only one parameter on getItem
Why use getElementById and onclick when you have jQuery?
My guess is you mean
function toggleAV(lang) {
$('.av-it').toggle(lang=="LangIT");
$('.av-en').toggle(lang=="LangEN");
localStorage.setItem('a_avlang', lang); // saves LangEN or LangIT
}
$(function() { // onload
$('.avlangbuttons').on("click", function(event) {
event.preventDefault(); // stop the click
toggleAV(this.id);
});
toggleAV(localStorage.getItem('a_avlang') || "LangEN"); // if exists otherwise english
});
Alternatively use data-attributes instead of parsing the ID

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

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 check if target is link

I have a global function to capture clicks.
$(document).click(function(e){
//do something
if(clickedOnLink)
//do something
});
I want to do additional stuff when the target is a link, but if the the <a> tag actually surrounds a div (as HTML5 allows this) the target will be that div.
http://jsfiddle.net/Af37v/
You can try to see if the element you clicked on either is or is a child of an <a> tag.
$(document).click(function(e){
if($(e.target).closest('a').length){
alert('You clicked a link');
}
else{
alert('You did not click a link');
}
});
I believe using is will actually have better performance than the answers suggesting closest:
$(e.target).is('a, a *');
This checks if the element itself is an a or if it is contained with an a.
This should be faster than closest because it will use matches on the element itself and not need to traverse up the DOM tree as closest will do.
Try this
$(document).click(function(e){
//do something
if($(this).closest('a').length)
//do something
});
If the exact target is link, then you can use .is()
Example:
$(".element").on("click", function(e){
if($(e.target).is("a")){
//do your stuff
}
});
EDIT:
If it is surrounded by other element that is inside an anchor tag, then you can use closest() and check whether it have anchor tag parent or not by using length
Example:
$(".element").on("click", function(e){
if($(e.target).closest("a").length){
//do your stuff
}
});
With jquery just get the tagName attribute
$("a").prop("tagName");
Updated:
You could check if the target is an a or if a parent is an a.
$(function () {
$(document).on('click', function (e) {
$target = $(e.target);
if ($target.closest('a').length > 0) {
alert('i am an a');
}
});
});
http://jsfiddle.net/8jeGV/4/
You can test if there's a <div> under <a> by testing if the .children() <div> has anything inside it. If nothing is inside, or there is no <div>, the if statement will return false.
I suggest this code:
$(document).click(function(e){
var willRedirect = ($('a[href="/"]').attr('href').indexOf('#') == -1 ? true : false),
//run code
if ( willRedirect === false ){
e.preventDefault();
//the link will not redirect
if ( $(this).children('div').html() ){
//there is a <div> inside <a> containing something
}
else {
//there is no <div> inside <a>
}
}
else {
//the link is not pointing to your site
}
});

How to hide a div if the user cicks anywhere on the page except 2 elements using jQuery?

I have the following markup:
Click Me
<div id="foo" style="border:1px solid red; display:hidden"></div>
My code to get the "foo" div to show on click.
$('#clickMe').click(function(e) {
$('#foo').show();
e.preventDefault();
});
Now how can I hide the div again IF THE USER CLICKS ANYWHERE ON THE PAGE EXCEPT THE DIV ITSELF OR THE CLICK ME LINK?
Note: I need to be able to do this without changing the markup.
$('#clickMe').click(function(e) {
$('#foo').show();
e.preventDefault();
});
$("#clickMe, #foo").mouseup(function(){return false;});
$(document).mouseup(function(e){//removes menu when clicked on any other part of page
if($("#foo:visible").length > 0 ){
$('#foo').hide();
}
});
Example on JSFIDDLE.net
Try this:
$(document).click(function() {
$("#foo").hide();
});
$("#foo, #clickMe").click(function() {
return false;
});
$('#clickMe, #foo').click(function() {
$('#foo').show();
return false;
});
$(":not(#clickMe, #foo)").click(function() {
$('#foo').hide();
});
Check it out on JSFiddle.
You can put a click handler on document.body so it gets clicks from every element on the page. You can check the target property of the event object to see what was actually clicked on and if it does not have the ID's of those two elements you can hide your <div>.
$(document.body).click(function(event){
var targetID = $(event.target).attr("id");
if( targetID !== "clickMe" && targetID !== "foo" ){
$("#foo").hide();
}
});
Try it out!

Categories

Resources