Skip to content

Unable to bind modal to elements added dynamically in DOM . #9671

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
sanjay-github opened this issue May 17, 2017 · 6 comments · Fixed by #25435
Closed

Unable to bind modal to elements added dynamically in DOM . #9671

sanjay-github opened this issue May 17, 2017 · 6 comments · Fixed by #25435
Assignees
Labels
bug report Issue: Clear Description Gate 2 Passed. Manual verification of the issue description passed Issue: Confirmed Gate 3 Passed. Manual verification of the issue completed. Issue is confirmed Issue: Format is valid Gate 1 Passed. Automatic verification of issue format passed Issue: Ready for Work Gate 4. Acknowledged. Issue is added to backlog and ready for development Reproduced on 2.1.x The issue has been reproduced on latest 2.1 release Reproduced on 2.2.x The issue has been reproduced on latest 2.2 release Reproduced on 2.3.x The issue has been reproduced on latest 2.3 release

Comments

@sanjay-github
Copy link

sanjay-github commented May 17, 2017

Preconditions

  1. Magento CE 2.1.6

Steps to reproduce

  1. Use a Magento_Ui/js/modal/modal to bind click event with any element.
  2. Now add a dynamic element say by ajax or any way you like.
  3. The click event is not bound to the element which is possible if it considers parent class which is already there in the DOM.
  4. Current solution is to override the modal.js and bind considering the parent element.

Expected result

  1. The click event should be bound to the new elements added to the DOM.

Actual result

  1. The click event is not bound to the new element.

This is my current solution if its right way to modify modal.js

Please check create() method.

/**

  • Copyright © 2013-2017 Magento, Inc. All rights reserved.
  • See COPYING.txt for license details.
    */

define([
'jquery',
'underscore',
'mage/template',
'text!ui/template/modal/modal-popup.html',
'text!ui/template/modal/modal-slide.html',
'text!ui/template/modal/modal-custom.html',
'Magento_Ui/js/lib/key-codes',
'jquery/ui',
'mage/translate'
], function ($, _, template, popupTpl, slideTpl, customTpl, keyCodes) {
'use strict';

/**
 * Detect browser transition end event.
 * @return {String|undefined} - transition event.
 */
var transitionEvent =  (function () {
    var transition,
        elementStyle = document.createElement('div').style,
        transitions = {
            'transition': 'transitionend',
            'OTransition': 'oTransitionEnd',
            'MozTransition': 'transitionend',
            'WebkitTransition': 'webkitTransitionEnd'
        };

    for (transition in transitions) {
        if (elementStyle[transition] !== undefined && transitions.hasOwnProperty(transition)) {
            return transitions[transition];
        }
    }
})();

/**
 * Modal Window Widget
 */
$.widget('mage.modal', {
    options: {
        type: 'popup',
        title: '',
        subTitle: '',
        modalClass: '',
        focus: '[data-role="closeBtn"]',
        autoOpen: false,
        clickableOverlay: true,
        popupTpl: popupTpl,
        slideTpl: slideTpl,
        customTpl: customTpl,
        modalVisibleClass: '_show',
        parentModalClass: '_has-modal',
        innerScrollClass: '_inner-scroll',
        responsive: false,
        innerScroll: false,
        modalTitle: '[data-role="title"]',
        modalSubTitle: '[data-role="subTitle"]',
        modalBlock: '[data-role="modal"]',
        modalCloseBtn: '[data-role="closeBtn"]',
        modalContent: '[data-role="content"]',
        modalAction: '[data-role="action"]',
        focusableScope: '[data-role="focusable-scope"]',
        focusableStart: '[data-role="focusable-start"]',
        focusableEnd: '[data-role="focusable-end"]',
        appendTo: 'body',
        wrapperClass: 'modals-wrapper',
        overlayClass: 'modals-overlay',
        responsiveClass: 'modal-slide',
        trigger: '',
        elementToBindWithTriggerAsParent: '',
        modalLeftMargin: 45,
        closeText: $.mage.__('Close'),
        buttons: [{
            text: $.mage.__('Ok'),
            class: '',
            attr: {},

            /**
             * Default action on button click
             */
            click: function (event) {
                this.closeModal(event);
            }
        }],
        keyEventHandlers: {

            /**
             * Tab key press handler,
             * set focus to elements
             */
            tabKey: function () {
                if (document.activeElement === this.modal[0]) {
                    this._setFocus('start');
                }
            },

            /**
             * Escape key press handler,
             * close modal window
             */
            escapeKey: function () {
                if (this.options.isOpen && this.modal.find(document.activeElement).length ||
                    this.options.isOpen && this.modal[0] === document.activeElement) {
                    this.closeModal();
                }
            }
        }
    },

    /**
     * Creates modal widget.
     */
    _create: function () {
        _.bindAll(
            this,
            'keyEventSwitcher',
            '_tabSwitcher',
            'closeModal'
        );

        this.options.transitionEvent = transitionEvent;
        this._createWrapper();
        this._renderModal();
        this._createButtons();
        if(this.options.elementToBindWithTriggerAsParent){
            $(this.options.trigger).on('click',this.options.elementToBindWithTriggerAsParent, _.bind(this.toggleModal, this));
        }else{
            $(this.options.trigger).on('click',_.bind(this.toggleModal, this));
        }
        this._on(this.modal.find(this.options.modalCloseBtn), {
            'click': this.options.modalCloseBtnHandler ? this.options.modalCloseBtnHandler : this.closeModal
        });
        this._on(this.element, {
            'openModal': this.openModal,
            'closeModal': this.closeModal
        });
        this.options.autoOpen ? this.openModal() : false;
    },

    /**
     * Returns element from modal node.
     * @return {Object} - element.
     */
    _getElem: function (elem) {
        return this.modal.find(elem);
    },

    /**
     * Gets visible modal count.
     * * @return {Number} - visible modal count.
     */
    _getVisibleCount: function () {
        var modals = this.modalWrapper.find(this.options.modalBlock);

        return modals.filter('.' + this.options.modalVisibleClass).length;
    },

    /**
     * Gets count of visible modal by slide type.
     * * @return {Number} - visible modal count.
     */
    _getVisibleSlideCount: function () {
        var elems = this.modalWrapper.find('[data-type="slide"]');

        return elems.filter('.' + this.options.modalVisibleClass).length;
    },

    /**
     * Listener key events.
     * Call handler function if it exists
     */
    keyEventSwitcher: function (event) {
        var key = keyCodes[event.keyCode];

        if (this.options.keyEventHandlers.hasOwnProperty(key)) {
            this.options.keyEventHandlers[key].apply(this, arguments);
        }
    },

    /**
     * Set title for modal.
     *
     * @param {String} title
     */
    setTitle: function (title) {
        var $title = $(this.options.modalTitle),
            $subTitle = this.modal.find(this.options.modalSubTitle);

        $title.text(title);
        $title.append($subTitle);
    },

    /**
     * Set sub title for modal.
     *
     * @param {String} subTitle
     */
    setSubTitle: function (subTitle) {
        this.options.subTitle = subTitle;
        this.modal.find(this.options.modalSubTitle).html(subTitle);
    },

    /**
     * Toggle modal.
     * * @return {Element} - current element.
     */
    toggleModal: function () {
        if (this.options.isOpen === true) {
            this.closeModal();
        } else {
            this.openModal();
        }
    },

    /**
     * Open modal.
     * * @return {Element} - current element.
     */
    openModal: function () {
        this.options.isOpen = true;
        this.focussedElement = document.activeElement;
        this._createOverlay();
        this._setActive();
        this._setKeyListener();
        this.modal.one(this.options.transitionEvent, _.bind(this._setFocus, this, 'end', 'opened'));
        this.modal.one(this.options.transitionEvent, _.bind(this._trigger, this, 'opened'));
        this.modal.addClass(this.options.modalVisibleClass);

        if (!this.options.transitionEvent) {
            this._trigger('opened');
        }

        return this.element;
    },

    /**
     * Set focus to element.
     * @param {String} position - can be "start" and "end"
     *      positions.
     *      If position is "end" - sets focus to first
     *      focusable element in modal window scope.
     *      If position is "start" - sets focus to last
     *      focusable element in modal window scope
     *
     *  @param {String} type - can be "opened" or false
     *      If type is "opened" - looks to "this.options.focus"
     *      property and sets focus
     */
    _setFocus: function (position, type) {
        var focusableElements,
            infelicity;

        if (type === 'opened' && this.options.focus) {
            this.modal.find($(this.options.focus)).focus();
        } else if (type === 'opened' && !this.options.focus) {
            this.modal.find(this.options.focusableScope).focus();
        } else if (position === 'end') {
            this.modal.find(this.options.modalCloseBtn).focus();
        } else if (position === 'start') {
            infelicity = 2; //Constant for find last focusable element
            focusableElements = this.modal.find(':focusable');
            focusableElements.eq(focusableElements.length - infelicity).focus();
        }
    },

    /**
     * Set events listener when modal is opened.
     */
    _setKeyListener: function () {
        this.modal.find(this.options.focusableStart).bind('focusin', this._tabSwitcher);
        this.modal.find(this.options.focusableEnd).bind('focusin', this._tabSwitcher);
        this.modal.bind('keydown', this.keyEventSwitcher);
    },

    /**
     * Remove events listener when modal is closed.
     */
    _removeKeyListener: function () {
        this.modal.find(this.options.focusableStart).unbind('focusin', this._tabSwitcher);
        this.modal.find(this.options.focusableEnd).unbind('focusin', this._tabSwitcher);
        this.modal.unbind('keydown', this.keyEventSwitcher);
    },

    /**
     * Switcher for focus event.
     * @param {Object} e - event
     */
    _tabSwitcher: function (e) {
        var target = $(e.target);

        if (target.is(this.options.focusableStart)) {
            this._setFocus('start');
        } else if (target.is(this.options.focusableEnd)) {
            this._setFocus('end');
        }
    },

    /**
     * Close modal.
     * * @return {Element} - current element.
     */
    closeModal: function () {
        var that = this;

        this._removeKeyListener();
        this.options.isOpen = false;
        this.modal.one(this.options.transitionEvent, function () {
            that._close();
        });
        this.modal.removeClass(this.options.modalVisibleClass);

        if (!this.options.transitionEvent) {
            that._close();
        }

        return this.element;
    },

    /**
     * Helper for closeModal function.
     */
    _close: function () {
        var trigger = _.bind(this._trigger, this, 'closed', this.modal);

        $(this.focussedElement).focus();
        this._destroyOverlay();
        this._unsetActive();
        _.defer(trigger, this);
    },

    /**
     * Set z-index and margin for modal and overlay.
     */
    _setActive: function () {
        var zIndex = this.modal.zIndex();

        this.prevOverlayIndex = this.overlay.zIndex();
        this.modal.zIndex(zIndex + this._getVisibleCount());
        this.overlay.zIndex(zIndex + (this._getVisibleCount() - 1));

        if (this._getVisibleSlideCount()) {
            this.modal.css('marginLeft', this.options.modalLeftMargin * this._getVisibleSlideCount());
        }
    },

    /**
     * Unset styles for modal and set z-index for previous modal.
     */
    _unsetActive: function () {
        this.modal.removeAttr('style');

        if (this.overlay) {
            this.overlay.zIndex(this.prevOverlayIndex);
        }
    },

    /**
     * Creates wrapper to hold all modals.
     */
    _createWrapper: function () {
        this.modalWrapper = $(this.options.appendTo).find('.' + this.options.wrapperClass);

        if (!this.modalWrapper.length) {
            this.modalWrapper = $('<div></div>')
                .addClass(this.options.wrapperClass)
                .appendTo(this.options.appendTo);
        }
    },

    /**
     * Compile template and append to wrapper.
     */
    _renderModal: function () {
        $(template(
            this.options[this.options.type + 'Tpl'],
            {
                data: this.options
            })).appendTo(this.modalWrapper);
        this.modal = this.modalWrapper.find(this.options.modalBlock).last();
        this.element.appendTo(this._getElem(this.options.modalContent));

        if (this.element.is(':hidden')) {
            this.element.show();
        }
    },

    /**
     * Creates buttons pane.
     */
    _createButtons: function () {
        this.buttons = this._getElem(this.options.modalAction);
        _.each(this.options.buttons, function (btn, key) {
            var button = this.buttons[key];

            if (btn.attr) {
                $(button).attr(btn.attr);
            }

            if (btn.class) {
                $(button).addClass(btn.class);
            }

            if (!btn.click) {
                btn.click = this.closeModal;
            }
            $(button).on('click', _.bind(btn.click, this));
        }, this);
    },

    /**
     * Creates overlay, append it to wrapper, set previous click event on overlay.
     */
    _createOverlay: function () {
        var events,
            outerClickHandler = this.options.outerClickHandler || this.closeModal;

        this.overlay = $('.' + this.options.overlayClass);

        if (!this.overlay.length) {
            $(this.options.appendTo).addClass(this.options.parentModalClass);
            this.overlay = $('<div></div>')
                .addClass(this.options.overlayClass)
                .appendTo(this.modalWrapper);
        }
        events = $._data(this.overlay.get(0), 'events');
        events ? this.prevOverlayHandler = events.click[0].handler : false;
        this.options.clickableOverlay ? this.overlay.unbind().on('click', outerClickHandler) : false;
    },

    /**
     * Destroy overlay.
     */
    _destroyOverlay: function () {
        if (this._getVisibleCount()) {
            this.overlay.unbind().on('click', this.prevOverlayHandler);
        } else {
            $(this.options.appendTo).removeClass(this.options.parentModalClass);
            this.overlay.remove();
            this.overlay = null;
        }
    }
});

return $.mage.modal;

});

@sanjay-github sanjay-github changed the title Binding modal considering parent element so as to support dynamic elements. Binding modal to elements added dynamicically in DOM . May 17, 2017
@sanjay-github sanjay-github changed the title Binding modal to elements added dynamicically in DOM . Binding modal to elements added dynamically in DOM . May 17, 2017
@sanjay-github sanjay-github changed the title Binding modal to elements added dynamically in DOM . Unable to bind modal to elements added dynamically in DOM . May 17, 2017
@mage-dave
Copy link

is there any update on this? I am having same issue

@magento-engcom-team magento-engcom-team added 2.1.x bug report Issue: Format is valid Gate 1 Passed. Automatic verification of issue format passed and removed G1 Passed labels Sep 5, 2017
@magento-engcom-team magento-engcom-team added Issue: Clear Description Gate 2 Passed. Manual verification of the issue description passed 2.2.x Issue: Ready for Work Gate 4. Acknowledged. Issue is added to backlog and ready for development Issue: Confirmed Gate 3 Passed. Manual verification of the issue completed. Issue is confirmed Reproduced on 2.1.x The issue has been reproduced on latest 2.1 release Reproduced on 2.2.x The issue has been reproduced on latest 2.2 release Reproduced on 2.3.x The issue has been reproduced on latest 2.3 release labels Nov 28, 2017
@magento-engcom-team
Copy link
Contributor

@sanjay-github, thank you for your report.
We've created internal ticket(s) MAGETWO-84637 to track progress on the issue.

@m2-assistant
Copy link

m2-assistant bot commented Nov 1, 2019

Hi @krzksz. Thank you for working on this issue.
Looks like this issue is already verified and confirmed. But if you want to validate it one more time, please, go though the following instruction:

  • 1. Add/Edit Component: XXXXX label(s) to the ticket, indicating the components it may be related to.

  • 2. Verify that the issue is reproducible on 2.3-develop branch

    Details- Add the comment @magento give me 2.3-develop instance to deploy test instance on Magento infrastructure.
    - If the issue is reproducible on 2.3-develop branch, please, add the label Reproduced on 2.3.x.
    - If the issue is not reproducible, add your comment that issue is not reproducible and close the issue and stop verification process here!

  • 3. If the issue is not relevant or is not reproducible any more, feel free to close it.


@krzksz
Copy link
Contributor

krzksz commented Nov 1, 2019

@magento give me 2.3-develop instance

@magento-engcom-team
Copy link
Contributor

Hi @krzksz. Thank you for your request. I'm working on Magento 2.3-develop instance for you

@magento-engcom-team
Copy link
Contributor

Hi @krzksz, here is your Magento instance.
Admin access: https://i-9671-2-3-develop.instances.magento-community.engineering/admin
Login: admin Password: 123123q
Instance will be terminated in up to 3 hours.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug report Issue: Clear Description Gate 2 Passed. Manual verification of the issue description passed Issue: Confirmed Gate 3 Passed. Manual verification of the issue completed. Issue is confirmed Issue: Format is valid Gate 1 Passed. Automatic verification of issue format passed Issue: Ready for Work Gate 4. Acknowledged. Issue is added to backlog and ready for development Reproduced on 2.1.x The issue has been reproduced on latest 2.1 release Reproduced on 2.2.x The issue has been reproduced on latest 2.2 release Reproduced on 2.3.x The issue has been reproduced on latest 2.3 release
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants