Image Slider - is it possible to enable keyboard navigation? (SOLVED)

Permalink
Does anyone know how to enable keyboard navigation (arrow keys) in a custom template for concrete5's build-in image slider?

Thank you,
Michael

okapi
 
okapi replied on at Permalink Reply
okapi
Found a solution.
In case anyone's interested, these lines of JS code enable keyboard navigation for the image slider block (arrow keys left and right) :

$(document).on('keyup.slider', function(evt) {
    if (evt.keyCode == 37) {
        $('.rslides_nav.prev').trigger('click');
    } else if (evt.keyCode == 39) {
        $('.rslides_nav.next').trigger('click');
    }
});

I added this to a custom template for the image silder block.
mnakalay replied on at Permalink Reply
mnakalay
beware that if you have more than one slider on the page they will all start sliding at the same time with this solution.

You could use a bID to namespace your slider or you could use the target of the event and get the closest next/prev buttons to trigger
okapi replied on at Permalink Reply
okapi
Hi Nour, yes, i see, thanks for pointing that out to me! If multiple sliders would be used on one page, the keyboard navigation should only be valid for the currently active slider, right?

What would that mean for the code if I used the bID? How would i have to do that? Can you please give me an example?
mnakalay replied on at Permalink Best Answer Reply
mnakalay
well each block has that unique identifier $bID. It is not 100% unique as if you copy a block to the clipboard and then add it to the page, it will get the same bID as the original unless you put it in edit mode and save.

But for our purpose it's good enough.

So first you have to make sure your JS script is in your template and not in a JS file.

then you make sure that, in your template, your slide's wrapper has a class name or an ID that uses that $bID so for instance
<div id="myslider<?php echo $bID; ?>">

Your wrapper will have an id of myslider445 for instance

then you add your code in the template at the bottom and use your wrapper ID
$(document).on('keyup.slider', function(evt) {
    if (evt.keyCode == 37) {
        $('#myslider<?php echo $bID; ?>').find('.rslides_nav.prev').trigger('click');
    } else if (evt.keyCode == 39) {
        $('#myslider<?php echo $bID; ?>').find('.rslides_nav.next').trigger('click');
    }
});

Of course you have to make sure your nav buttons are inside that wrapper. If they are right outside of it, use the same principle but instead of find() maybe use siblings()
okapi replied on at Permalink Reply
okapi
Thank you so much, this is a much better solution and it works great!