Question

I was trying to apply arrow navigation to an image gallery using jQuery's trigger() method.

I got an example of that from another stackoverflow user and it seemed to be fine but when I added real links to the list items they would only load when clicked and not when the arrow keys were pressed.

In this JSfiddle the last two list items, "apple" and "microsoft" have the real links, they should load the pages onto the iFrame when they're activated by the arrow keys but they don't. They only properly work when clicked.

How do I make the key presses equal to the clicks?

var chosen = "";
$(document).keydown(function(e){ // 38-up, 40-down
    chosen = $('li.selected').index(); //grab the current selection
    if (e.keyCode == 40) { 
        if(chosen === "") {
            chosen = 0;
        } else if((chosen+1) < $('li').length) {
            chosen++; 
        }
        selectImage(chosen);
        return false;
    }
    if (e.keyCode == 38) { 
        if(chosen === "") {
            chosen = 0;
        } else if(chosen > 0) {
            chosen--;            
        }
        selectImage(chosen);
        return false;
    }
});

function selectImage(whichIndex) {
    $('li:eq('+whichIndex+') a').trigger("click");
}
$("#selection a").click(function() {
    $('li').removeClass('selected'); 
    $(this).parent().addClass('selected');

    $("#debug").text( $(this).attr("href") +" was just clicked");   
});
Was it helpful?

Solution

The .trigger() function will only cause the handler methods that you attached with jQuery to execute. It will not cause the normal behavior of the <a> elements to execute. That is, it will not load the <iframe>.

You could use e.preventDefault() to prevent the <a> element from performing its default behavior, and add code that performs it explicitly. That way, it will execute both when it is clicked and when .trigger() is called.

In your case, you would need to set the src property of the <iframe>.

Try changing the event handler to this:

$("#selection a").click(function(e) {
    var $a = $(this);
    e.preventDefault();
    $a.parent().addClass('selected').siblings().removeClass('selected');
    $('iframe[name=iframeload]').prop('src', $a.attr('href'));
    $("#debug").text( $a.attr("href") +" was just clicked");   
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top