Search code examples
javascripthtmlbutton

Issue with simulating keystroke on button click event


I'm trying to emulate arrow key strokes using JS. I'm not experienced in JS, but I found some code that does what I want. The issue is that I cannot get it to properly work with two buttons.

HTML:

<button id="simA_plain" style="float: right; width: 50%">Simulate arrow left, no plugin</button>
<button id="simB_plain" style="float: right; width: 50%">Simulate arrow left, no plugin</button>

JS:

$("#eventTarg").bind ("keydown keypress keyup change",  function (zEvent) {
    $("#eventLog").append ('<span>' + zEvent.type + ': ' + zEvent.which + ', </span>');
} );

$("button").click ( function (zEvent) {
    if (zEvent.target.id == "simA_plain") {
        var keyVal = 39;
        $("#eventTarg").trigger ( {
            type: 'keypress', keyCode: keyVal, which: keyVal, charCode: keyVal
        } );
    }
} );


$("button").click ( function (zEvent) {
    if (zEvent.target.id == "simB_plain") {
        var keyValb = 37;
        $("#eventTarg").trigger ( {
            type: 'keypress', keyCode: keyValb, which: keyValb, charCode: keyValb
        } );
    }
} );

The issue is that when I click on the button with the ID simB_plain, it simulates the right key "39," not the intended "37." For context, I'm trying to use this to advance slides in a google sheets embed on my website by simulating right/left arrow strokes. However, it will only move the slides forward, which means is still simulating 39.

You can see that it should function as intended in this modified jsfiddle: https://jsfiddle.net/c4ywmqhn/7/, but when I implement it on my site, it still only simulates "39"


Solution

  • I couldn't find a solution with JS, but I found one using a feature of the Google Sheets Slides embed system. For anyone faced with the same issue, this is what I did:

    <div class="responsive-google-slides">
        <iframe name="col" src="https://docs.google.com/presentation/d/e/XXXX/embed?start=true&loop=true&delayms=3000&rm=minimal" frameborder="0" width="960" height="569" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>
    
        <!--The following two buttons enable navigation with buttons.-->
        <a class="prev" href="https://docs.google.com/presentation/d/e/XXXX/embed?start=true&loop=true&delayms=3000&rm=minimal#slide=previous" target="col">&#10094;</a>
        <a class="next" href="https://docs.google.com/presentation/d/e/XXXX/embed?start=true&loop=true&delayms=3000&rm=minimal#slide=next" target="col">&#10095;</a>
    </div>
    

    Basically, I added buttons which changed the iframe link to the spreadsheet link with #slide=previous or #slide=next appended on it.