I'm having trouble getting an onMouseDown
function that takes each link and copies the original HREF attribute of its respective anchor tag in a page and loads the URL on the down event.
Let's call this function loadURL()
.
Right now I'm testing the function in-line for each anchor and am having trouble getting different values for each HREF attribute. I would like to make an onLoad
function that essentially adds the onMouseDow
n attribute and loadURL
function to every anchor. Here's the JQuery code I have now.
PROBLEM SOLVED, SHOWING INITIAL PROBLEM FOR REFERENCE
Script:
function loadURL()
{
var url = $('a').attr('href');
location.href = url;
}
function mouseDownerURL () {
$('a').attr('onmousedown', 'loadURL()' );
}
HTML
<body onLoad="mouseDownerURL();">
<a onmousedown="" href="foo.com">Takes you to foo.com on mouseDown</a>
<a onmousedown="" href="bar.com">Leads to foo.com NOT bar.com on mouseDown</a>
</body>
SOLUTION
function mouseDownerURL() {
$(document).ready(function() {
$('a').mousedown(function() {
window.location.href = this.href;
});
});
}
<body onLoad="mouseDownerURL();">
<a href="1">1</a>
<a href="2">2</a>
...
Get rid of all of those functions and onload
things and just do it normally:
$(document).ready(function() {
$('a').mousedown(function() {
window.location.href = this.href;
});
});
Your problem is this line:
var url = $('a').attr('href');
$('a')
selects all of the <a>
tags, not the one that was clicked. To work around that, you have to pass the element into your function via an argument, but that's not a great idea.