0

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 onMouseDown 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>
...
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
DAF487
  • 3
  • 5

1 Answers1

0

Get rid of all of those functions and onload things and just do it normally:

$(document).ready(function() {
    $('a').mousedown(function() {
        windows.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.

Blender
  • 289,723
  • 53
  • 439
  • 496
  • for some reason this isn't triggering onMouseDown. I'm placing this code within script tags after sourcing jQuery and it's not having any affect. Firefox btw. – DAF487 Feb 18 '13 at 22:40
  • the 's' in windows.location.href was breaking this. Removing it solved the issue. Thanks a ton! – DAF487 Feb 18 '13 at 23:01