jQuery check if target is link - javascript

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

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

Open page based on $(this) selector

I'm modifying a wordpress site and have a menu with four anchor tags (buttons) to the left of a slider. When a user selects a button, the slide associated with the button shows. Now, I'd like to open a page when the user clicks the button, instead of showing the slide. Here is the code so far:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$a = $(this);
$(this).showSlide();
if($a.id == $('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Here I'm testing to see if I can click on the anchor with the id '#slide-1285' and log it to the console. It always says 'not testing'. I'm going to set up conditions for all id's so a user is redirected to the correct page. Something like this:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$(this).showSlide();
if($a.id == $('#slide-1285')){
window.location.href = "http://webpage1";
}
elseif($a.id == $('#slide-1286')){
window.location.href = "http://webpage2";
}
elseif($a.id == $('#slide-1287')){
window.location.href = "http://webpage3";
}
else($a.id == $('#slide-1288')){
window.location.href = "http://webpage4";
}
});
Any ideas? Thanks in advance.
To get the id of the element that was clicked, you can do:
$(this).attr('id');
That will return a string. So you could do:
if($(this).attr('id') === 'slide-1285') { do something }
$('#slide-1285') would return a jquery element, but you want just the id. I think the code above is more what you are looking for.
You can add a new data attribute to each of your link and then get that value and redirect.
<a data-webpage="http://webpage1" href="whatever" id="slide-123"></a>
<a data-webpage="http://webpage2" href="whatever" id="slide-456"></a>
.....
and then
// this will bind all ids starting with slide-
$('[id^=slide-]').on('click', function(e){
// some code.
window.location.href = $(this).data('webpage');
}
1) you are comparing $a.id, that is string, to object $('#slide-1285');.
2) To simplify:
$(document).ready(function(){
$('.a').click(function(e){
e.preventDefault();
window.location = $(this).attr('href');
});
});
<a href='http://google.com' class='a'>Google!</a><br/>
<a href='http://stackoverflow.com' class='a'>SO!</a><br/>
jQuery objects have no id property. You need to do attr('id'), or just get the id property of the plain DOM object. Additionally, jQuery objects are never going to equal each other. Third, you want to check if the clicked element has a certain ID, which can be done using .is().
In sum, you could do one of these:
Comparing strings:
$('#slidernavigation > a').on('click', function(e){
if(this.id == '#slide-1285'){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Using .is():
$('#slidernavigation > a').on('click', function(e){
if($(this).is('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Or, just let the browser do its thing. Give your <a>s href attributes, and they'll function as links, even without JS.
instead of writing $.id
you should write
$a.attr('id')
and this should be checked like this :-
if( $a.attr('id') == slide-1285)
not the way you are doing :)
Try
var pages = [{"slide-1285" : "http://webpage1"}
, {"slide-1286" : "http://webpage2"}
, {"slide-1287" : "http://webpage3"}
, {"slide-1288" : "http://webpage4"}
];
$('#slidernavigation > a').on('click', function(e) {
e.preventDefault();
var nav = e.target.id;
$.grep(pages, function(page) {
if (nav in page) {
window.location.href = page[nav];
}
})
});
jsfiddle http://jsfiddle.net/guest271314/2nf97dfr/
<div id="a">
dhjdfd
</div>
$('#a').on('click',function(e){
var clickedElement= e.srcElement;
if($(clickedElement).attr("id") == "abc"){
//do something
}
});
just use e.srcElement to get the element reference and then get its id.. and btw u can use switch case rather than multiple if else statements ..
working fiddle link

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

jQuery if Element has an ID?

How would I select elements that have any ID? For example:
if ($(".parent a").hasId()) {
/* then do something here */
}
I, by no means, am a master at jQuery.
Like this:
var $aWithId = $('.parent a[id]');
Following OP's comment, test it like this:
if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)
Will return all anchor tags inside elements with class parent which have an attribute ID specified
You can use jQuery's .is() function.
if ( $(".parent a").is("#idSelector") ) {
//Do stuff
}
It will return true if the parent anchor has #idSelector id.
You can do
document.getElementById(id) or
$(id).length > 0
You can using the following code:
if($(".parent a").attr('id')){
//do something
}
$(".parent a").each(function(i,e){
if($(e).attr('id')){
//do something and check
//if you want to break the each
//return false;
}
});
The same question is you can find here: how to check if div has id or not?
Number of .parent a elements that have an id attribute:
$('.parent a[id]').length
Simple way:
Fox example this is your html,
<div class='classname' id='your_id_name'>
</div>
Jquery code:
if($('.classname').prop('id')=='your_id_name')
{
//works your_id_name exist (true part)
}
else
{
//works your_id_name not exist (false part)
}
I seemed to have been able to solve it with:
if( $('your-selector-here').attr('id') === undefined){
console.log( 'has no ID' )
}
Pure js approach:
var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));
JsFiddle Demo
Simply use:
$(".parent a[id]");
You can do this:
if ($(".parent a[Id]").length > 0) {
/* then do something here */
}
You can use each() function to evalute all a tags and bind click to that specific element you clicked on. Then throw some logic with an if statement.
See fiddle here.
$('a').each(function() {
$(this).click(function() {
var el= $(this).attr('id');
if (el === 'notme') {
// do nothing or something else
} else {
$('p').toggle();
}
});
});

jquery: get mouse click if inside a div or not

i have this HTML page
<html>
<body>
<div>a</div>
<div>b</div>
<div>c</div>
<div>d</div>
<div id='in_or_out'>e</div>
<div>f</div>
</body>
</html>
a,b,c,d,e and f could be divs also not just a plain text.
I want to get the mouse click event, but how could i know if it's inside or outside #in_or_out div ?
EDIT :: guys, i know how to check if the div is click or not, but i want my event to be fired when the click is outside that div
$("body > div").click(function() {
if ($(this).attr("id") == "in_or_out") {
// inside
} else {
// not inside
}
});
EDIT: just learned, that there is a negate:
$("body > div:not(#in_or_out)").click(function(e) {
// not inside
});
If you want to detect whether or not you've clicked inside or outside the div, set the event handler on the documentElement and let it propagate from the other elements upwards:
$("html").click(function (e)
{
if (e.target == document.getElementById("in_or_out"))
alert("In");
else
alert("Out!");
});
Maybe this one will help you
$('body').click(function(){
//do smth
});
$('div#in_or_out').click(function(e){
e.stopPropagation();
// do smth else
});
Depends what you want. If you only want to execute code, when it was inside #in_or_out, you can do:
$('#in_or_out').click(function(){ /* your code here */ });
You can have a status variable that says whether the mouse is in #in_or_out or not:
var inside = false;
$('#in_or_out').hover(function() { inside = true; }, function() { inside = false; });
Then whenever a click occurs you can check with inside whether the click was inside in_or_out or not.
Reference: .hover()
Update:
No matter to which element you bind the click handler, you can always do this:
$('element').click(function() {
if ($(this).attr('id') !== 'in_or_not') {
}
});
for inside it would be
$("#in_or_out").click(function() {
// do something here
});
for outside...I've got no idea.
Edit: You could try to do the same for body-tag (assigning a click-handler to the document itself). But I'm not sure if both events would fire by that.
Like this?
$("#in_or_out").click(function() {
alert("IN DIV!");
});

Categories

Resources