patrick
patrick

Reputation: 11721

trigger a click on a anchor link

I have a collection of links with thumbnails that match them. I need to load these thumbnails as divs with the background image set to them. I'm using a single image that has all thumbnails in them, so I can't just load the images as images. Clicking the image should do the same as clicking the link though, I made a JSFiddle to show what I mean (and to show the problem):

the JSFiddle

When I click the two links in there a new window is opened which has the site I want. But when I click the thumbnails I can't get a click on the link triggered.

Clicking of the link will have extra functionality (stats), so I prefer to trigger a click on the link over binding the same custom function to both the anchors and the divs.

Thanks in advance

Upvotes: 1

Views: 10036

Answers (2)

dvd
dvd

Reputation: 1034

In HTML4 the click event was defined only for the input element and some browser, most notably FF, strictly followed the specification. However HTML5 the game changed and any modern browser implements this functionality, but jQuery still has a special case for this event (extract from jquery trigger method):

if ( !onlyHandlers && !event.isDefaultPrevented() ) {

    if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {

    // Call a native DOM method on the target with the same name name as the event.

As a workaround you can change your code from:

target.trigger("click");

to

target.get(0).click();

Upvotes: 7

Tats_innit
Tats_innit

Reputation: 34107

Hiya Working demo here: http://jsfiddle.net/f6FJ3/19/

for the trigger reason read this : jQuery: trigger click() doesn't work?

It's important to clarify that doing jQuery('#open').click() does not execute the href attribute of an anchor tag so you will not be redirected. It executes the onclick event for #open which is not defined.

below code will get the desired output of window getting open on image click.

JQuery Code

$(document).ready(function(){
    $('.tmb').click(function(){
        var target=$(this).parent().find("a");

        $("#debug").text("clicked "+target.text());
        //target.triggerHandler('click');
        window.open(target.attr('href'));

    });
});​

Hope this helps, cheers!

Upvotes: 5

Related Questions