E
E
Evanre2015-10-07 11:00:15
JavaScript
Evanre, 2015-10-07 11:00:15

How to implement delayed start of a function?

There is a future online store. According to the layout in the product blocks, there are 2 types of displaying the number of products: span and input.
7bcd2b3cda9e426ea8c5220921f1bfe8.png
Behavioral logic: initially only the span is displayed. When you click on it, it changes to an input and the focus is transferred to it (it becomes possible to change the number of units of the product.) After losing the focus, hide the input and show the span, passing the number that was entered in the input into it.

Initially, the implementation was simpler. Banal input.amount and span.amount selectors. Everything worked fine in Chrome. But Ms. FireFox caused a lot of problems.

$("span.amount").click(function() {
    $(this).addClass('hidden');
    $(this).siblings("input.amount").removeClass('hidden').focus();
  });
  $("input.amount").focusout(function() {
    $(this).addClass('hidden');
    $(this).siblings("span.amount").removeClass('hidden').html($(this).val() + ' шт.');
  });

Through long debugging, it was found out that this script does not work in FF (or rather, it works but very quickly, the focus loss function is instantly called), because the focusout() function had a too general selector $("input.amount" ) (as I understand the logic, there are many such elements on the page, and only one of them has focus). It was decided to "cling" only to a specific input and not to all at once.
var inputCurrent = '';
  $('input.amount').hide();// при загрузке прячем все инпуты
  $('span.amount').click(function() { // клик по спану
    var inputCurrent = $(this).siblings('input.amount'); // передаем в переменную текущий инпут
    $(this).hide(); // прячем текущий спан
    inputCurrent.show().focus(); // показываем текущий инпут и передаем ему фокус
  });
  inputCurrent.focusout(function() { // при потере инпутом фокуса:
    $(this).hide(); // прячем этот инпут
    $(this).siblings('span.amount').show().html($(this).val() + ' шт.'); // показываем текущий спан и передаем в него параметры из инпута
  });

This is a more correct option, but it does not work in its current form, because. The focusout() function is executed before the inputCurrent variable is defined. As a result, we have focusout is not a function.

Can you please tell me how to run the focusout() function only after the inputCurrent variable is defined? Thank you.

ps. I have very little experience and knowledge in js and jquery, so I'll forgive you if this code is written crookedly :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GreatRash, 2015-10-07
@Evanre

Everything is wrong with you, too gemorno. Instead of a span , make a label and only track focus and blur on the input.
codepen.io/anon/pen/LpyXWa

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question