I need to be able to get the href (or somehow get the target url) of any <a> tag that is clicked even if it is wrapping another element. For example, you could ordinarily do:
$("document").click(function (event) {
url = event.target.href;
});
However, in this example, the <a> wraps an <img>, so the event target will not have the href. Using parentNode is no good either, because there is also a span around the img in the example:
http://jsfiddle.net/z7ZYw/
I cannot change the selector either.
So is there any way to get the href in this circumstance?
You're looking for jQuery's closest method:
$(e.target).closest('a');
As a note, this can be done without jQuery aswell:
var href = (e.target.parentNode && e.target.parentNode.href) ? e.target.parentNode.href : e.target.href;
You need to bind only on anchor tags:
$("a[href]").click(function () {
console.log($(this).attr("href"));
});
Related
I have an AJAX function which populates a div with spans of data into a template. I would like to append these spans to links, which when clicked call a function. With what I do have, it does seem an href link is getting added, but the text itself is still not clickable.
Here's the html from the IDE as well as from the developer tools in IE :
<div id="subtotal_menu">
</div>
Here's what I have tried so far:
var $menu = $('#subtotal_menu');
$menu.empty();
$('#checkTemplate').tmpl(data.d.Checks).appendTo($menu);
$("#subtotal_menu").find("span").attr('href','myfunction()');
Also tried to create a separate function to operate on the DOM element:
function createVendorInvoiceLinks() {
var subTotalmenu = document.getElementById("#subtotal_menu").find("span");
var aTag = document.createElement('a');
aTag.setAttribute('href', "myfunction()");
subTotalmenu.appendChild(aTag);
}
This could help you:
var $menu = $('#subtotal_menu');
$menu.find("span").append('Link');
// append an anchor to the span inside #subtotal_menu
// set javascript:void(0) as href to avoid unwanted behaviour on click
$('#subtotal_menu').on('click', 'a',function(){
alert('clicked');
// do whatever myfunction() does
});
//set up a proper event handler and use event-delegation to cope with
//dynamic added element from e.g. your mentioned ajax-request
When you want the whole span to be clickable just change the binding from the event handler from a to span. This way you don't event need to append an anchor.
Example
Reference
jQuery .append()
event delegation
Instead of appending the <a> element to the span, you should do the opposite:
function createVendorInvoiceLinks() {
var subTotalmenu = document.getElementById("#subtotal_menu").find("span");
var aTag = document.createElement('a');
aTag.setAttribute('href', "myfunction()");
aTag.appendChild(subTotalmenu);
}
So you don't generate a <a> with no content.
we are trying to create a custom cms where when inside anchor tag you put a rel attribute and a target position and it automatically attach a click that can fetch data from specified location in rel tag. again new content(came through ajax) can have anchor tag with rel attribute.
how can i achieve it without using callback
current code
$(document).ready(function(e) {
$("a[rel $= txt]").each(function(index, element) {
$(this).click(function(){
var path = $(this).attr("rel");
path = "./"+path;
var target = $(this).attr("data-target")
$(target).load(path, function(){
$("a[rel $= txt]", this).each(function(){
$(this).click(function(){
var path = $(this).attr("rel");
path = "./"+path;
$("#result").load(path,function(){
$.getScript("js/common.js")
});
})
});
$.getScript("js/common.js");
})
})//click ended
});
})
You can use $(match-expression).live('click',function(){}) to attach a click handler to all matching elements, even those that are created dynamically later. In your case, $("a[rel $= txt]").live('click',function(){}) will allow you to attach a click handler to all matching anchors.
I'm using jQuery to get a click on an 'a' element. I have a list of those links where each one has a class which by him I'm capturing the click.
I would like to know which of the links has been clicked (I have an attribute 'setid' for each link) and also get the point where the mouse has been clicked.
How could this be accomplished?
example of the code:
click me
$('.newItem').click(function (e) {
alert(e.attr('setid'));
});
EDIT:
OK, so to get the position I would use e.pageX
To use jQuery methods you have to wrap this with a call to jQuery.
$('.newItem').click(function () {
alert($(this).attr('setid'));
});
refer to the code given below:
document.getElementById("element_id").addEventListener("click",function(e)
{
console.log(e.srcElement.getAttribute("data-name"));
},false);
Like Skylar said in the comment to your question, you can use "data-" in front of your new attribute (which is HTML5 valid).
click me
Then in jQuery (v1.4.3+) you can get it like:
var setid = $(this).data("foo");
It's even a little nicer than attr() that other people have mentioned. See this for more examples - http://www.broken-links.com/2010/11/18/data-attributes-in-html-and-jquery/
You're on the correct path.
$(function(){
$('.newItem').click(function () {
alert( $(this).attr('setid') );
})
});
Your code is almost right to get the attribute. The only thing missing is wrapping this (a DOM element) in the jQuery wrapper so you can use jQuery functions. $(this).attr('setid') should work.
To get the page coordinates, use the pageX and pageY properties of the event object. So:
$('.newItem').click(function (e) { // e is the event object
alert($(this).attr('setid'));
alert(e.pageX);
alert(e.pageY);
});
See the documentation on the Event object.
I am trying to add an onClick event to an anchor tag ...
Previously i had ...
<a href="somlink.html" onClick="pageTracker._link(this.href); return false;">
But i am trying to avoid the inline onClick event because it interferes with another script..
So using jQuery i am trying the following code ...
<script>
$(document).ready(function() {
$('a#tracked').attr('onClick').click(function() {window.onbeforeunload = null;
pageTracker._link(this.href);
return false;
});
});
</script>
with the html like so <a id="tracked" href="something.html">
So my question is should this be working, and if not what would be the best solution?
The correct way would be (as for jQuery)
$('#tracked').click(function() {
pageTracker._link($(this).attr('href'));
return false;
});
This will add an "onclick" event on any element with tracked id. There you can do anything you want. After the click event happens, the first line will pass href attribute of the clicked element to pageTracker.
As for your original question, it wouldnt work, it will raise undefined error. The attr works a bit different. See documentation . The way you used it, would return the value of the attribute and I think that in that case its not chainable. If you would like to keep it the way you had it, it should look like this:
$('#tracked').click(function() {
$(this).attr('onclick', 'pageTracker._link(this.href); return false;');
return false;
});
You can also try
var element1= document.getElementById("elementId");
and then
element1.setAttribute("onchange","functionNameAlreadyDefinedInYourScript()");
// here i am trying to set the onchange event of element1(a dropdown) to redirect to a function()
I spent some time on this yesterday. It turned out that I needed to include the jQuery on $(window).ready not $(document).ready.
$( window ).ready(function() {
$('#containerDiv a').click(function() {
dataLayer.push({
'event': 'trackEvent',
'gtmCategory': 'importantLinkSimilarProperties',
'gtmAction': 'Click',
'gtmLabel': $(this).attr('href')
});
});
});
Is it possible to hide the href without hiding the whole anchor tag?
Click Me
The reason I need this is because I'd need to hide and show it based on desktop and mobile view controlled by JS.
Something like $('a').attr('href').hide(); won't work
Edit:
I need to 'hide' the href so I can 'show' it where I need to. Removing the href will not restore it.
You can use removeAttr():
$('a').removeAttr('href');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click Me
Description: Remove an attribute from each element in the set of matched elements
If you want to hide the href but still want it to redirect when clicked, use this.
Get the URL and put it in data attribute. Then remove the href attribute.
$('a').each(function() {
$(this).data('href', $(this).attr('href')).removeAttr('href');
});
When clicked on anchor, get the URL from data attribute and redirect.
$('a').on('click', function() {
window.location.href = $(this).data('href');
});
But what if You want to restore href? From where will You get it?
<div class="some-container">
Click Me
Click Me
</div>
function hideHrefs(selector) {
$(selector).each(function(){
var $this = $(this);
var href = $this.attr('href');
$this.attr('href', '').data('href', href);
});
}
function restoreHref($element) {
var href = $element.data('href');
$element.attr('href', href);
}
hideHrefs('.some-container a'); // hides all hrefs from links in container element
restoreHref($('.some-container a:first')); // restores href for dedicated element
Is it possible that when you don't want the href you do something like this
$($.find("a")).attr("href", "#")