Search code examples
javascriptjquerymodal-dialogpopupmagnific-popup

Magnific Popup focus button on open


I'm using the Magnific Popup plugin and I would like to make my main action button (Save), focused when the pop up opens so that if a user clicks the enter key, it simply triggers a click event.

I tried doing the following on the console with no luck:

$('.popup-modal-save').focus();

Is there a way of doing this without using a key down event listener?

Here is a link to my JSFiddle: https://jsfiddle.net/dwjfq1gp/25/


Solution

  • You can use the focus option of magnific-popup.

    $.magnificPopup.open({
        items : {
        type : 'inline',
        src : '#idOfInlinePopUP'
        },
        focus: '#closeButton',                                                                   
        closeOnBgClick:false,                                                                        
        enableEscapeKey:false
        }, 0);
    

    Code of button:

    <input type="button" value="close" onclick="$.magnificPopup.close();" id="closeButton">
    

    In this code the focus option consists of the ID of the button which you want to open. And src has to contain the id of the inline popup.

    If you are able to open your popup successfully then you just need to add focus attribute with ID of the button you want to click on enter click.

    In this answer, on opening of popup the default focus will be on closeButton. On clicking this button the popup will close.