Create onclick method with href - javascript

I want to create AJAX versions of links where possible. For this I want to have a function replaceLinks which create a onClick handler for each link on the page which then calls ajaxPageWSM(href). I have this:
function replaceLinks() {
$("a").click(function() {
...
});
}
How can I access the href inside the function?

var a_href = $(this).attr('href');

You can get the href like this:
function replaceLinks() {
$("a").click(function() {
var href = $(this).attr("href");
});
}

I'm not sure you even need anything other than this.href. So like:
function replaceLinks() {
$("a").click(function() {
var href = this.href;
});
}

Try this:
function replaceLinks() {
$("a").on("click", function(event) {
var href=event.currentTarget.href;
});
}

Related

Can't get the href value of an anchor tag with jQuery

I'm trying to get the href value of an anchor tag using jQuery, but the this keyword is not working as expected.
Here is the result of the code in the console:
The part of the code I have problem with:
$('#container a').click(() => {
console.log(this);
let link = $(this).attr("href");
console.log("from jquery - " + link);
//chrome.tabs.create({ url: link });
});
As you can see, the this keyword is pointing on the window object.
This code is part of an extension I'm trying to build for Opera.
You are using an arrow function () => {..} instead of a regular function function () {...}, that's why your this didn't work as you've expected.
So instead of this:
$('#container a').click(() => { ... });
Use this:
$('#container a').click(function() { ... });
Your updated code:
$('#container a').click(function () {
console.log(this);
let link = $(this).attr('href');
console.log(link);
})
OR with an arrow function:
$('container a').click(event => {
let link = $(event.currentTarget).attr('href');
console.log(link);
})
More on arrow functions:
Concise article from Wes Bos
Good video from MPJ
MDN documentation
This will give you the href value
var href = $('a').attr('href');
Here is a sample to test here:
$(document).ready(function() {
$("a").click(function(event) {
var href = $(event.target).attr('href'); //this will give you the href value
alert(href);
event.preventDefault();
});
});
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
this is a test link, click me
Don't use the arrow function (() => {}) use classic function declaration (function() {}). Arrow functions don't bind this to the current scope.
$("#container a").click(function(){
console.log(this);
let link = $(this).attr("href");
console.log(link);
})
You can learn more about arrow functions here.

Generate url only when anchor is clicked

Is it possible to assign url to the an anchor only when it got clicked?
Token Link
When the anchor got clicked, it will go to http://example.com/token=xxxxx/
I want to generate token only when it got clicked.
If possible, How?
thanks
you can handle the event and change the href like this.
$("a").on("click", function() {
$(this).attr("href", $(this).attr("href") + "/token=xxxx");
});
you can also directly navigate the user to a different url, without changing.
$("a").on("click", function(ev) {
document.location.href = "//something-different.com";
ev.preventDefault();
return false;
});
Opening the link in another window using jQuery
$(document).ready(function () {
$(".thisClass a").on("click", function(e){
e.preventDefault(); // this prevents going to the original url or default behavior
var changedLink = $(this).attr("href", $(this).attr("href") + "/token=xxxx");
var newUrl = $(changedLink).attr('href');
window.open(newUrl, '_blank');
});
});
// Here is a way to do it with Plain Javascript - i did not test it on all browsers but worked with chrome for example.
// goes in a script.js or in script tags under the </body> element
function changeTheLink() {
event.preventDefault();
var aLink = document.getElementById('theLink');
var theOldLink = aLink.getAttribute("href");
aLink.setAttribute('href', theOldLink + "/token=xxxx");
var theNewLink = aLink.getAttribute("href");
window.open(theNewLink, "_blank");
}
// here is the HTML you owuld have to add an id and an onclick attribute to use this code
<div class="thisClass"><a href="http://thiswebsite.com" id="theLink"
onclick="changeTheLink()">Here is a link</a></div>

how can i add an attribute onClick oto my links generated automatically?

I would like to add an attribute onClick to my links generated automatically with jquery.
I select the parent div and then search if it has a link child, then add the attribute onClick.
It works on localhost but not on server
there is my code :
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function () {
if ($(this).children('a').hasClass('holder_notify_drop_link')) {
$(this).on('click', function (e) {
var url = $(this).children('a').attr('href');
$(this).children('a').attr('onClick', "openFrame('" + url + "','yes')");
e.preventDefault();
});
};)
};
How can i do this ?
Make sure you include jQuery:
<script src="http://code.jquery.com/jquery-latest.js"></script>
IMPORTANT: Also put your code inside a document-ready function and I would suggest you to use jQuery click() function instead of the way you have done, but that's okay:
$(document).ready(function () {
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function(){
if ($(this).children('a').hasClass('holder_notify_drop_link')){
$(this).on('click',function(e) {
var url = $(this).children('a').attr('href');
$(this).children('a').attr('onClick',"openFrame('"+url+"','yes')");
e.preventDefault();
});
};
)};
});
Here's a working example http://jsfiddle.net/g248G/.
HTML:
<div class="holder_notify_drop_data">
<a class="holder_notify_drop_link"
href="http://stackoverflow.com">Stackoverflow.com</a>
</div>
<ul>
<li class="holder_notify_drop_data">
<a class="holder_notify_drop_link"
href="http://google.com">Google.com</a>
</li>
</ul>
Javascript:
function openFrame(URL, option) {
window.open(URL);
}
$(document).ready(function() {
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function() {
$(this).children('a').each(function() {
var $link = $(this);
if ($link.hasClass('holder_notify_drop_link')) {
var URL = $link.attr('href');
$link.on('click', function(event) {
event.preventDefault();
openFrame(URL, 'yes');
});
}
});
});
});
Why not use jQuery.on() for that?
This will bind click function to all current and future elements of a in holder_notify_drop_data container.
$('.holder_notify_drop_data').on('click', 'a', function (ev) {
ev.preventDefault();
openFrame($(this).prop('href'), 'yes');
});

Get ID of Element Being Clicked and Pass as Parameter?

How does one, through jQuery, get the ID of an element that is being clicked on and then pass it as a parameter into a function? Example jQuery code below.
jQuery(document).ready(function() {
var id = this_id;
jQuery(".lightbox a").click({param: id}, functionName);
});
May I note that the "param" parameter is integral to the structure of the function.
Apologies all, I am no Javascript master by any means.
I'm guessing the point is to pass event data to a function that expects that, as ,click() supports the .click( [eventData ], handler(eventObject) ) syntax, and if so, you have to iterate the collection yourself:
jQuery(document).ready(function($) {
$(".lightbox a").each(function() {
$(this).click({param: this.id}, functionName);
});
});
EDIT:
You could do this with on() as well:
jQuery(document).ready(function($) {
$(".lightbox a").each(function() {
$(this).on('click', {param: this.id}, functionName);
});
});
FIDDLE
Within the click handler, you can access the element ID with this.id or $(this).attr('id'):
jQuery(document).ready(function() {
jQuery(".lightbox a").click(function(){
functionName(this.id);
});
});
You can use this.id inside a click event, example:
jQuery(".lightbox a").click(function() {
var id = this.id;
//pass to a function
testFunction(id);
});
function testFunction(param) {
console.log(param);
}
It's easy just access to the this element to get the clicked element, then extract its id and save it into a variable like this:
jQuery(".lightbox a").click(function(){
var id = jQuery(this).attr("id");
callFunction(id);
});
http://jsfiddle.net/pArW6/
jQuery(document).ready(function() {
jQuery(".lightbox a").click(functionName);
});
function functionName()
{
alert(this.id);
}
You can you Use $(this).att("id").
$(".lightbox a").click(function() {
var ID=$(this).att("id");
//pass to a function
TestFunction(ID);
});
function TestFunction(P) {
console.log(P);
}
Live example
http://jsbin.com/enobop/1/edit
You can do this:
jQuery(document).ready(function () {
jQuery(".lightbox a").click(function (e) {
// Cancel the default action (navigation) of the click.
e.preventDefault();
// 'this' here refers to the link being clicked in the current scope
// you can check the console for the id for debug purpose
console.log(this.id);
// pass the id to the function
functionName(this.id);
});
});
Another way is to use the event parameter that gets passed to the callback function.
jQuery(".lightbox a").click(function(ev) {
console.log(ev.target.id);
}
Of course it's a mix of jQuery and pure JS.
Usually you have a function for an event declared with
function(event)
and the event has a target and the id of the target is, what you want. So
$("SomeElement").on("click", function(e){ callanotherFunction(e.target.id) })
does, what you wanted
You can use this.id or $(this).attr("id");, but you might want to get a reference to $(this) - wrapped or not - immediately and work from a variable if you do much of anything else in there.

Jquery mouseover function not firing

I have this Jquery code:
$(document).ready(function() {
// Do menu mouseovers
$('.bar a').each(function() {
var Link = $(this);
var LinkID = Link.attr("ID");
$('.menu-pop').each(function() {
var PopID = $(this).attr("data-for");
// We have found a match, assign events
if (PopID == LinkID) {
Link.mouseover = (function() {
alert("trucks lol");
});
return;
}
});
});
});
It's for a popup menu I'm writing. The simplified structure of the menu is:
<div class="bar">
<a class="item">Home</a>
<a class="item" id="mnuAnother">Another Link</a>
</div>
<div class="menu-pop" data-for="mnuAnother">
Links and stuff
</div>
I'm expecting it to do the alert when my mouse goes over the "Another" link, but at present it throws no errors/no alert.
Any help appreciated.
Did you try
Link.mouseover(function() {
alert("trucks lol");
});
(using jQuery's mouseover function which is a shortcut for binding the mouseover event)
See: http://jsfiddle.net/rQ72v/
Change this:
Link.mouseover = (function() {
alert("trucks lol");
});
to this:
Link.mouseover(function() {
alert("trucks lol");
});
Link.mouseover = doesn't really make any sense.
Perhaps Link.onmouseover = would work (or would you need Link[0].onmouseover =?) in terms of raw JavaScript.
But, it's much better to use jQuery's .mouseover().
I would replace the
// ...
$('.bar a').each(function() {
var Link = $(this);
// ...
by something line
// ...
$('.bar a').each(function(item) {
var Link = $(item);
// ...

Categories