I have div and over it is link with absolute position div. I need to catch click event on link and get "href" attribute. I don't want to use any library only plain JavaScript. Is it possible?
I tried something like this but it catches only div outside of link.
window.addEventListener('load', function ()
{
document.addEventListener('click', $openExternalLink, false);
});
function $openExternalLink(e) {
alert(e.target.tagName);
}
HTML:
<div>Text</div>
<div style="position: absolute; left: ..., top: ..."></div>
Maybe this structure is terrible unfortunately I cannot influence it.
Thank you
document.onload = function() {
var myLink = document.querySelector("a");
myLink.addEventListener("click", function() {
var href = this.href;
})
}
Simply add an event listener to your anchor, then get its href attribute with this.href (or this.getAttribute("href"))
I'll assume you're fairly new to JavaScript? if so, definitely go check out http://CodeCademy.com/
Also, something I just though of, if you want to handle the link with a function (as it seems you do), do something like this instead:
document.onload = function() {
var myLink = document.querySelector("a");
myLink.addEventListener("click", function(e) {
e.preventDefault(); // Makes the event prevent the default link behaviour
var href = this.href;
externalLink(href);
})
}
externalLink(href) {
// Do something with your link.
// perhaps, window.location = href (or whatever)
}
To use for ALL links on a page (as per your comment), do the following:
document.onload = function() {
var links = document.querySelectorAll("a");
var i = 0, count = links.length;
for (i; i < count; i++) {
links[i].addEventListener("click", function(e) {
e.preventDefault();
externalLink(this.href);
})
}
}
externalLink(href) {
// Do something with your link.
// perhaps, window.location = href (or whatever)
}
Used querySelectorAll to target ALL anchor tags in the document, and then for-looped through them, adding an event listener to each. Keep in mind, this script needs some tweaking if you also want to support IE8. (using attachEvent("onclick"... instead of addEventListener, and replacing this with links[i] within the event)
Related
I'm trying to make a script that, when you click on an anchor, a $.get function will get the anchor's href and then the href will be removed, but I cannot edit anything about the anchor from inside de get element. Example:
// make anchor disappear for example (doesn't work)
$('.belovedanchor').click(function(e) {
$.get($(this).attr('href')).done(function() {
$(this).hide();
});
});
// make an anchor disappear using a function (doesn't work too)
$('.belovedanchor').click(function(e) {
function do() { $(this).hide(); };
$.get($(this).attr('href')).done(function() {
do();
});
});
I don't understand why $(this) change to work with the $.get function istead of the .click event.
How would you guys do it?
You have a couple problems. Edit: Only one problem -- I now see from your comment below that belovedanchor is not the actual selector in your code.
First, your jQuery selector for the click event handler is most likely incorrect. Change $('belovedanchor') to $('.belovedanchor') or $('#belovedanchor') depending if the anchor is identifiable by either class or element ID respectively.
Second, this in the do callback function does not refer to the anchor. In JavaScript, scope is set at the function level, so anytime you declare a new function, this will refer to that new scope.
Do this instead:
$('belovedanchor').click(function(e) {
var anchor = $(this);
function do() { anchor.hide(); };
$.get($(this).attr('href')).done(function() {
do();
});
});
Simplified:
$('belovedanchor').click(function(e) {
var anchor = $(this);
$.get(anchor.attr('href')).done(function() {
anchor.hide();
});
});
This may work properly
$('.belovedanchor').click(function() {
var selectedancor = $(this);
var myurl = $(this).attr('href');
$.get(myurl, function() {
selectedanchor.hide();
});
});
I'm new to JavaScript and am unsure how to do the following:
I've got two links with the same css "class" but different "name" attributes. I need to perform different functions to each one individually when clicked using unobtrusive Javascript. Is there anyway to do this?
Example code:
<a class="ClassName" name="link1">Link 1</a>
<a class="ClassName" name="link2">Link 2</a>
Lets say I need to output "This is link 1" to the console when I click link 1. And "this is link 2" when Link 2 is clicked.
Attach an event handler to the elements, and just check the name and do whatever you'd like
var elems = document.querySelectorAll('.ClassName');
for (var i=elems.length; i--;) {
elems[i].addEventListener('click', fn, false);
}
function fn() {
if ( this.name == 'link1' ) {
console.log('This is link1');
} else if ( this.name == 'link2' ) {
console.log('This is link2');
}
}
FIDDLE
You can do like in this JS Fiddle Demo , its pretty simple:
JS:
var anchorTags = document.querySelectorAll('.ClassName');
for (var i = 0; i < anchorTags.length; i++) {
anchorTags[i].onclick = function() {
alert(this.innerHTML);
}
}
Hope this helps.
It's not very performant but you can use name selectors. .className[name=link1] however, if you have multiple links the best way to handle something like this is to use event delegation. It's really easy if you have access to jquery
I would do something like
parent.on('click', '.ClassName', function(event) {
var button = $(this),
name = button.attr(name);
switch(name):
case link1
case link2
...
});
this way you don't have to assign individual events to the different links. You could also do something like this without event delegation if you really wanted to it would just be changing it to
var links = $('.ClassName');
links.on('click', function() {
...
});
Keep in mind that the latter will attach an eventHandler to each link.
If you don't have jQuery you can still do this you just need to grab the elements differently and handle attachEvent vs addEventHandler. Also, applying the delegation will require delving into the event.currentTarget object.
something like:
var parent = document.getElementById('parentid');
parent.addEventListener('click', function(event) {
if (event.currentTarget.getAttribute('class')indexOf('ClassName') > -1) {
... do stuff w/ that link here
}
});
I am trying to write a pure JavaScript function (means no jquery).When a user clicks a link ( a tag) I wanted to run a javascript function. I Googled for a solution but did't find what I was looking for. Below is the jquery solution, I want a pure JavaScript event listener which listens to a href click. There is no id or class attached to tags. ex: <a href='xxxx'>xxxx</a>
This is what I have (using jquery)
$('a').click(function(e) {
var regExp = new RegExp('//'+location.hostname+'($|/)');
var href = $(this).attr('href');
if (regExp.test(href)) { e.preventDefault();
var i = (((href.split('?')[1]).split('/')[0]).split('&')[1]).split('=')[1];
activityFeedClick(event,i); } });
I need to convert the above jquery to javascript, basically I need to convert " $('a').click(function(e) " this to a pure JavaScript event listener.
Thanks.
Short answer:
var myFunction = function(e) {
var regExp = new RegExp('//'+location.hostname+'($|/)');
var href = this.href; // please notice this replacement here
if (regExp.test(href)) {
e.preventDefault();
var i = (((href.split('?')[1]).split('/')[0]).split('&')[1]).split('=')[1];
activityFeedClick(event,i);
}
}
var links = document.querySelectorAll('a');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click', myFunction);
}
You can use "document.getElementsByTagName" to get a nodelist of all "a" elements in the DOM,
then loop through them and use "addEventListener".
This has the advantage of being supported in browsers without support for queryselector.
Add an onclick event on anchor tags like this.
click me
How can i get the action performed by an hyperlink inside an div using javascript
<div id="example">
<a href="#">a<a>
b
c
</div>
var links = document.getElementById('example').getElementsByTagName('a');
links[0].onclick = function(){
alert('a clicked');
}
links[1].onclick = function(){
alert('b clicked');
}
links[2].onclick = function(){
alert('c clicked');
}
Working Example
you can attach event handlers in the loop as well:
var links = document.getElementById('example').getElementsByTagName('a');
for(var i = 0;i < links.length; i++){
links[i].onclick = function(e){
var event = e || window.event;
alert(e.target.innerHTML + ' link was clicked!!!');
}
}
I am guessing you are coming from a java background. So, action performed is not available by default in JavaScript. Neither is an anchor or <a>, an anchor is generally used to link to an external or internal links.
Goes to a mypage.html
Where As what you are asking by action performed is events. For that you should do something like this
Test Link
What this above link does is, executes a javascript function name test();
function test() {
alert('ok the action is performed');
return false; //so that the browser does not decides to navigate after the function is executed
}
Some javascript libraries will give you some workaround for this. Here is an basic example done in JQuery
$("#example a">.click(function() {
//now you have got the action performed work around.
// You can use this as you like
// $this represent the item that was clicked
});
For this functionality in core. #Headshota answers is good example.
#Headshota example of referencing all the links within a div is reasonable, I'm merely expanding on it. I'm not sure what you mean by the action of a link so I'm assuming that you mean the url it points to and perhaps the target (deprecated).
var links = document.getElementById('example').getElementsByTagName('a');
links[0].onclick = function(){
// `this` inside this handler points to the <a> element that has been clicked
var href = this.href //where the link points
var target = this.target //if required
//do something with href and target
return false; //don't follow the link
}
etc...
$("#example a").click(function() {
alert("action");
});
What im trying to do is when the p inherits the class "active" that div.test will print the link rel correctly.
Currently if the page loads without the class assigned to the p tag, it will not. How can I make it happen when the p tag inherits the class "active" the link printed in div.test will get the rel printed correctly?
$(document).ready(function(){
var relvar = $('p.active').attr('rel');
$("div.test").html("<a rel='"+ relvar +"'>hello</a>");
$("p").click(function () {
$(this).toggleClass("active");
});
});
I am not sure what you asking. Are you saying that you would like this code:
var relvar = $('p.active').attr('rel');
$("div.test").html("<a rel='"+ relvar +"'>hello</a>");
To be run whenever the <p> element changes classes? If so, there is no "onchangeclass" event or anything like that, but you could actually create your own event to handle this:
$('p').bind('toggleActive', function() {
if($(this).hasClass('active')) {
var relvar = $(this).attr('rel');
$("div.test").html("<a rel='"+ relvar +"'>hello</a>");
}
}).click(function() {
$(this).toggleClass('active').trigger('toggleActive');
});
Check this code in action.
This is actually kind of roundabout - it would be simplest to just do the logic in the click handler itself. The main advantage of moving it to its own event is that if you then need to do this elsewhere in the code you can keep that logic separate and just "trigger" it as you need.
Not quite sure if this is what you are going for, but can you not handle it in the click code?
$(document).ready(function() {
$('p').click(function() {
$(this).toggleClass('active');
if ($(this).hasClass('active')) {
relvar = $(this).attr('rel');
$('div.test').html("<a rel='" + relvar + "'>hello</a>");
} else {
$('div.test').html("<a>hello</a>");
}
});
});
As far as I know, you will have to bind to some event in order for it to check and see if it needs to update the div.