BigMon
BigMon

Reputation: 61

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/

Upvotes: 1

Views: 1527

Answers (3)

Jennis Vaishnav
Jennis Vaishnav

Reputation: 341

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.

Upvotes: 2

Sifat Haque
Sifat Haque

Reputation: 6067

You actually need to listen the keypress event for that. And when the modal is opened then you need to attach the focus event. Here is a working fiddle https://jsfiddle.net/2fb3d841/1/

// I've just added this
callbacks: {
    open: function() {
            $('.popup-modal-save').focus();
            $(document).keypress(function(e){
              if (e.which == 13){
                  $(".popup-modal-save").click();
                  $.magnificPopup.close();
              }
            });
    },
}

Upvotes: 0

yaya
yaya

Reputation: 8273

you should use events to focus on save button when popup opened. fiddle

$('.popup-modal').magnificPopup({
   ...
    callbacks: {
        open: function() {
                $('.popup-modal-save').focus();
        },
    }
});

Upvotes: 0

Related Questions