S
S
Serqwezxc2021-07-10 18:37:42
JavaScript
Serqwezxc, 2021-07-10 18:37:42

Shorten Jquery code for opening popup windows?

https://codepen.io/SergeyYmsk/pen/XWRjgGe . There are two popups. They have two identical scripts, but they open with different buttons, how can I shorten the code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-07-10
@Serqwezxc

For buttons and their corresponding popups, add data attributes with the same values. Type, data-popup="log"and data-popup="reg"windows, data-open-popup="log"and data-open-popup="reg"buttons. When you click on the button, look at the value of the attribute, open the corresponding window. Closing the window - remove the click handler on .popup-close, in the click handler on documentadd a check that the target element is inside .popup-close. Everything:

$('[data-open-popup]').click(function(e) {
  e.stopPropagation();
  $(`[data-popup=${this.dataset.openPopup}]`).addClass('popup--open');
  $('header').addClass('popup--blur');
  $('body').addClass('popup--lock');
});

$(document).click(function(e) {
  const $target = $(e.target);
  if (!$target.closest('.popup__content').length || $target.closest('.popup__close').length) {
    $('.popup').removeClass('popup--open');
    $('header').removeClass('popup--blur');
    $('body').removeClass('popup--lock');
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question