How to make the event work and get the data?

Notifications are loaded in my system, with some notifications and a click on them, a modal window with data for example tasks should open.

The script that shows the modal window connects to the page at the time of its loading and waits for click events.

The code that shows the window:

// показать задачу $('.view-task').on('click', function () { var id_cabinet = $(this).data('id-cabinet'); var id_task = $(this).data('id-task'); $modal.modal('show'); $modal.addClass('modal-task'); $modal.find('.modal-body').empty().end(); ... }); 

Downloadable notification code with data parameters

 <div data-notification="37259" data-notification-vid="tasks" class="notification-line leads view-task" data-lead-id="68413" data-id-cabinet="950" data-id-task="4318"> <div class="notification-lead-namb"><span class="ucrmicon">J</span> Задача по клиенту: #68413</div> <div class="notification-info-rem">замер</div> <div class="notification-date">Вчера в 13:00</div> </div> 

The code for showing the window is used on many pages of the site. How can I make minimal opening of the window so that the window opens when I click on the loaded item?

    2 answers 2

    Decided so:

     $('body').on('click', '.view-task', function(){ ... } 

      Elementary - to catch click on the container / wrapper and, through delegation , to work on the message.

       let template = `<div data-notification="%d5" data-notification-vid="tasks" class="notification-line leads view-task" data-lead-id="%d5" data-id-cabinet="%d3" data-id-task="%d4"> <div class="notification-lead-namb"><span class="ucrmicon">J</span> Задача по клиенту: #%d5</div> <div class="notification-info-rem">замер</div> <div class="notification-date">Вчера в %d24:%d60</div> </div>`, // Шаблон для показа уведмлений, рад разнообразия цифры меняются. Just for lulz wrapper = null; function showModal(){ // this - это элемент контейнера уведомления let m = new Modal(), // Создаём модальное окно, класс ниже c = `Ваша заявка по номером ${this.dataset.idTask} показана в модальном окне!`; // Контент m.show(c); // Показываем } document.addEventListener('DOMContentLoaded', e => { document.querySelector('#showNotification').addEventListener('click', getNotification); // Ищем обёртку (wrapper) и вешаем слушатель клика на него wrapper = document.querySelector('#wrapperNotification'); wrapper.addEventListener('click', e => { // Создание делегирования (подробнее по ссылке выше) // Если есть data-notification, вызываем обработчик let el = e.target, box = el.closest('[data-notification]'); if(!box || !wrapper.contains(box)) return; showModal.call(box); }); }); // Вспомогательные функции function random(min, max){return Math.floor(Math.random() * (max - min) + min);} function getNotification(){ if(wrapper.children.length > 2) return; wrapper.insertAdjacentHTML('beforeEnd', template.replace(/%d(\d+)/g, (z, num) => { let hs = false; num = +num; if(num === 24) hs = random(0, 24); else if(num === 60) hs = random(0, 60); if(hs !== false) return hs.toString().length === 1 ? '0' + hs : hs; return random(+'1'.repeat(num), +'9'.repeat(num)); })); } class Modal{ constructor(){ let t, c; this.wrapper = (t = document.createElement('div')) && (t.id = 'wrapperModal') && t; this.content = (c = document.createElement('div')) && (c.id = 'modalContent') && c; this.hasContent = false; t.addEventListener('click', this.hide.bind(this)); document.body.appendChild(t); t.appendChild(c); } show(data){ if(this.wrapper !== null && !this.hasContent){ this.wrapper.style.display = 'flex'; if(data instanceof HTMLElement) this.content.apperdChild(data); else this.content.innerHTML = String(data).trim(); this.hasContent = true; } } hide(){ if(this.wrapper !== null) this.wrapper.style.display = 'none'; } remove(){ this.wrapper = null; this.content = null; } } 
       /* Просто для наглядности работы */ html, body{ width: 100%; height: 100%; padding: 0; margin: 0; } #wrapperNotification{ position: absolute; bottom: 1%; right: 1%; } [data-notification]{ position: relative; cursor: pointer; max-width: 100%; max-height: 30%; margin-bottom: 10px; padding: 5px; border: 1px solid rgba(100,100,100,.3); } .notification-info-rem{ padding-left: 6%; } .notification-date{ font: 10pt Palantino Linotype; color: gray; position: absolute; bottom: 2px; right: 2px; } #wrapperModal{ position: fixed; top: 0; left: 0; display: none; width: 100%; height: 100%; z-index: 9999; background: rgba(0,0,0,.6); } #modalContent{ width: 50%; height: 50%; background: white; border: 1px solid black; margin: auto; box-sizing: border-box; padding: 10px; } 
       <input type='button' id='showNotification' value='Показать уведомление' /> <div id='wrapperNotification'></div>