How can I get the href of an anchor when I click on it using JavaScript?
I did the following:
function myFunc() {
}
window.onclick = myFunc;
But how to extend the function to respond only to clicks on anchors and get the href?
function linkClick(e) {
alert(e.target.href);
}
links = document.getElementsByTagName('a');
for (i = 0; i < links.length; i++)
links[i].addEventListener('click', linkClick, false);
Your document.onclick registers the handler on the whole document. But you should add it to every link. You can do this with JavaScript and using a framework like Prototype or jQuery makes it a lot easier:
$$('a').invoke('observe', 'click', function(a){
myFunc(a);
});
But you can also use pure JS combining the getElementsByTagName function with a loop (see Delan's new answer).
it won't work like this, you need to setup an onclick handler for every anchor. The easiest way to do this, is to use a javascript framework like jQuery or Prototype or something similar.
extend your function to recieve the calling object:
var myFunc = function(target) {
var href = target.href;
// ... your function code that can now see the href of the calling anchor
}
jQuery:
$('a').click(function(){
myFunc(this);
});
Protype: see Kau-Boy's answer
function myFunc(link) {
alert(link.href);
return false; // return false if you don't want to actually navigate to that link
}
<a href onclick="return myFunc(link)">something</a>
Related
I am having this code right now, which works just fine with links with an ID.
var buttonclick = document.getElementById("myLink");
buttonclick.addEventListener("click", function(event){
event.preventDefault(); window.location = 'facebook.com'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
google
What I want to do is get all links without an ID, just the ones which contain the world 'google' in the href attribute, and apply the same events further in my original code.
I have tried combining with jQuery, and all I managed to do is:
$('a[href*="google"]')
I am not sure how to combine it with the code above. Thank you in advance.
You can do it with document.querySelector(selector),
var buttonclick = document.querySelector('a[href*="google"]');
buttonclick.addEventListener("click", function(event){
event.preventDefault();
window.location = 'facebook.com'
});
If you want to target all the elements matches the selector then just use querySelectorAll instead of querySelector.
document.querySelectorAll('a[href*="google"]').forEach(function(button){
button.addEventListener("click", function(event){
event.preventDefault();
window.location = 'facebook.com'
});
});
Edited to use the function forEach belongs to nodeList object. It was inspired from #rory's answer.
You can achieve this by using a click() handler in your jQuery code. Try this:
$('a[href*="google"]').click(function(e) {
e.preventDefault();
window.location.assign('http://facebook.com');
});
If you'd prefer to stick with plain JS, then you can use querySelectorAll(), like this:
[].forEach.call(document.querySelectorll('a[href*="google"]'), function(el) {
el.addEventListener('click', function(e) {
e.preventDefault();
window.location.assign('http://facebook.com');
});
});
First a short background. So I just started practicing using API's. With the one I'm working with right now, I'm loading a DIV which have alot of links in it which I have to give a new purpose. I managed to prevent the default onclick-function. Now I need do save the clicked link "innerHTML" attribute.
var nextPage = document.getElementsByTagName("a")[this].innerHTML;
with [this] I tried to target the clicked link, but it didn't work. Hopefully you understands what I'm trying to do. If so, is there any way I an solve this problem?
Thanks!
EDIT:
$("#content, a").click(function(event){
event.preventDefault();
var x = document.getElementsByTagName("a")[0].innerHTML;
console.log(x)
getPage(x);
});
You can add an onclick listener to all the a tags elements
var links = document.getElementsByTagName('a');
for (var i = 0, il = links.length; i < il; i++) {
links[i].onclick = clickHandler;
}
function clickHandler(event) {
console.log(this.innerHTML);
}
<a>Link a</a>
<a>Link b</a>
first the document.getElementsByTagName("a")[this].innerHTML; will return undefined because it will return a collection of html node and it must pass index not the this.
Since you already have a click you can try this code :
function yourClickFunction(event) {
var target = event.target || event.srcElement;
var nextPage = target.innerHTML;
}
Use jQuery for this:
$('a').on('click', function(){
// this will run with every click, and 'this' will be your clicked item
console.log(this.innerHTML);
// although you probably want:
console.log($(this).attr('href'));
});
Using jQuery makes your code much cleaner, and unifying the cross browsers compatibility issues you might have when handling directly with the DOM api.
this.innerHTML can do the work, if I am getting you correctly.
If you are getting the entire html in it, you can bind an onclick event to the anchor itself and can work on that if that is possible.
<a onclick="clicked(this)">Click me</a>
function clicked(element) {
// Do whatever needed
// element.innerHTML will change it's innerHTML
}
You can it like the following too
$("#content, a").click(function(event){
event.preventDefault();
event.target.innerHTML = "Whatever";
})
You could use a common class (link in the below example) to attach the click event then just use this.innerHTML to return the text of you clicked link.
Hope this helps.
var classname = document.getElementsByClassName("link");
var clickFunction = function(){
//Prevent default
if ( event.preventDefault ) event.preventDefault();
event.returnValue = false;
//Get text
console.log(this.innerHTML);
}
for(var i=0;i<classname.length;i++){
classname[i].addEventListener('click', clickFunction, false);
}
<a href='link-1' class='link'>Link 1</a>
<a href='link-2' class='link'>Link 2</a>
<a href='link-3' class='link'>Link 3</a>
document.getElementsByTagName("a") gives you an array of HTMLAnchorElement. The indexes of the array are integer values from 0 to n.
this in your context i think it's the windows object (your code example is a bit short so i have to guess a bit)
using window as the index for the array that expects an integer of course gives you nothing. or undefined to be precise.
There're two possible ways to do what you're looking for:
onclick handler
function hello(elem) {
console.log("you clicked on '" + elem.innerHTML + "'")
}
click me
Here i'm using the onclick property and I pass the this context from the html as an argument to the function i'm calling. This is important.
Now i can operate on the element that was clicked just by referencing the argument received.
I would not suggest this method for a number or reasons. But since you mention the onclick property in the question ...
click event handler
this would be my preferred solution
function hello(evt) {
var elem = event.target || event.srcElement;
console.log("you clicked on '" + elem.innerHTML + "'");
}
var link = document.getElementsByTagName("a")[0]
link.addEventListener("click", hello)
click me
Here there's no code (or reference to the code) in the html. You instead retrieve the HTMLAnchorElement from the code and attach a listener to the click event.
Now the event handler will be called whenever the link is clicked and it will receive an event object by default. From that object you can extract the target (the object that generated the event) and access its properties.
In my application I need to disable double click href links. There are many jsf pages which used primeface links . So change everywhere is not a feasible solution.
Could anyone suggest that, is there any common function which we can achieve this functionality.
I tried override window.onbeforeunload function. But couldn't surpass that confirmation window and I couldn't achieve my desired objective from it.
Could I write any common javascript or jquery function to do this?
If you wish to disable all <a> tag double click then you might use this function.
$(document).ready(function(){
$(document).on("a","dblclick",function(event){
event.preventDefault();
return false;
});
});
Or if you wish to disable all <a> tag double click and also click then you might use this function.
$(document).ready(function(){
$(document).on("a","dblclick click",function(event){
event.preventDefault();
return false;
});
});
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++)
{
links[i].bind('dblclick',function(event){
event.preventDefault();
});
}
I think this should work.
If I have code like this:
<script>
function determine()
{
// ????
}
</script>
blah1
blah2
Is there a way in determine() to see which link was clicked?
(Yes, I know, the easy and correct thing to do would be to pass this to determine(), but in this case that's not going to be easy to do because of legacy code issues.)
EDIT: I probably should have mentioned this at the beginning...our site is not currently using (and cannot use, for the time being) jQuery, so jQuery answers (while valuable in general for this type of question) won't actually help me.
Check out this link from quirksmode. You can get the event target.
function doSomething(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
}
You can with straight up JavaScript, but I prefer to use something like jQuery:
blah1
<script type="text/javascript">
$('a[href=blah1]').click(function() {
var link = $(this); // here's your link.
return false; // acts like the link was not clicked. return true to carry out the click.
});
</script>
Assuming you are using the $().click() functionality, $(this) will give you the link.
If you cannot change the onclick="determine()" in your HTML, but you can change the determine() function, then I think your best bet is to:
Leave the determine() function blank so it doesn't do anything.
Use javascript (as described by other answers) to add a real click handler to each link, and use the event to determine which link was clicked then execute the desired code.
you could add events to each link like so
links = document.getElementsByTagName('a');
for (link in links) {
link.onclick = function() {
alert(this.id);
determine(); // or some other important code?
}
}
Another solution:
Add an onclick handler to the document. When a user clicks the link, the click event will "bubble" up to the window, and you will have access to the event to determine which link was clicked.
This might be useful if you only want the code to run for those links that already have onclick="determine()" - you could set the determine() function to set a variable. Then when the user clicks the link, the determine() function runs to set the variable, and when the document click handler runs you could check for the variable - then you will know that the link had onclick="determine()".
Let me know if I can make this a little more complicated for you... :-)
If you can't change the onclick attribute, patch it via JavaScript:
// use a DOMContentLoaded hack or `onload` as fallback
onload = function() {
var links = document.links;
for(var i = 0; i < links.length; ++i) {
// there might be a better way to check which links to modify
// don't know without further details
if(/determine\(\)/.test(links[i].onclick))
links[i].onclick = determine;
}
};
function determine() {
// the link is now available as `this`
alert(this.href);
}
Perhaps an even better solution would be to patch in a global, IE-style event object for standards compliant browsers:
if(document.addEventListener) {
document.addEventListener('click', function(e) {
window.event = e;
}, true);
}
function determine() {
var src = event.target || event.srcElement;
alert(src.href);
}
How do you change the JavaScript that will execute when a form button is clicked?
I've tried changing its onClicked and its onclicked child attributes like so:
$('mybutton').onClick = 'doSomething';
and
$('mybutton').attributes["onclick"] = 'doSomething()';
Neither seem to work. My other options are:
To have two buttons and hide one and show the other.
To have it directed to a function that evals a string and change the string to the function I want to execute.
Neither seem very elegant.
I'm using Prototype as a js library so it that has any useful tools I can use them.
If the original onclick event was set through HTML attributes, you can use the following to overwrite it:
$("#myButtonId").setAttribute("onclick", "myFunction();");
For Prototype, I believe that it would be something like this:
$("mybutton").observe('click', function() {
// do something here
});
EDIT: Or, as it says in the documentation, you could simply specify the function you want to call on click:
$('mybutton').observe('click', respondToClick);
function respondToClick(event) {
// do something here
}
But this is all, again, Prototype-specific.
Using the Prototype framework you can do:
Event.observe("mybutton", "click", clickHandler);
or:
Event.observe("mybutton", "click", function() {
alert("Button clicked!");
});
or:
$("mybutton").observe("click", clickHandler);
or:
$("mybutton").observe("click", function() {
alert("Button clicked!");
});
See the Event class documentation
The general way to set an onclick handler in javascript is to set onclick to a function, by passing it the name of a function directly, not in a string. So if myButton is set to a DOM Element, you would write:
myButton.onclick = doSomething;
So when you click the 'mybutton' button, the doSomething function will be called as doSomething(). For anonymous functions, you can write:
myButton.onclick = function() {
alert("myButton was clicked!");
};
In JQuery it's
$("#myButtonId").click(myFunction);
function myFunction(){
alert("Clicked");
}
Or if you want to put the function inline:
$("#myButtonId").click(function(){
alert("Clicked");
});
If you are using JQuery firstly make sure you use the relevant selector prefix (IE: If your using the Id of the element put a # in front of it). Secondly it's the click method to assign a callback to the click event.
Last I used Prototype, it was something like this:
Event.observe('mybutton', 'click', doSomething);
By the way, your examples might've even worked if you didn't quote the function names.
EDIT: Yes, Element.observe(element, eventName, handler) and someElement.observe(eventName, handler) also work. And don't quote the handler name - you want to pass the function not a string!
I found a solution for your issue with prototype under firefox:
$("#myButtonId").writeAttribute('onclick', ''); // first remove the attribute
$("#myButtonId").observe('click', function () { ... }); // then add the event