this is my simple requirejs-config.js file
var config = {
deps: ['js/custom']
};
and this is my custom.js file
define([
"jquery",
"domReady!"
],
function($) {
"use strict";
$("input").blur(function(){
alert("This input field has lost its focus.");
});
});
why blur alert does not works?
But if i call it with an event it works?
$(window).on('scroll', function() {
$("input").blur(function(){
alert("This input field has lost its focus.");
});
});
Also other jquery function does not works on domready and i need to call it with an event
1 Answer 1
It's hard to say without seeing your DOM structure, my guess is the input is rendered via JS (most of the checkout/minicart is) so it hasn't actually loaded at the point you add your event handler. If this is the problem using event delegation should resolve this:
Try this:
$("body").on("blur", "input", function(){
alert("This input field has lost its focus.");
});
It's good practice to change body to the closest parent element that is not rendered via JS.
For more info on event delegation see here - https://learn.jquery.com/events/event-delegation/
-
works fine thanks! is there a way to use an event delegation also for select2? $('select').select2();Altravista– Altravista2018年08月23日 06:25:31 +00:00Commented Aug 23, 2018 at 6:25
-
You can add more elements into the second argument, for example replace
"input"with#selector1, #selector2, .class1etc.Ben Crook– Ben Crook2018年08月23日 09:22:43 +00:00Commented Aug 23, 2018 at 9:22 -
but i cannot use "blur" with a div? I need to start select 2 in every pages witch event listener can i use?Altravista– Altravista2018年08月23日 10:17:29 +00:00Commented Aug 23, 2018 at 10:17
-
I rarely use blur so I'm not too sure sorry, you could try the focusout event in jQuery - api.jquery.com/focusoutBen Crook– Ben Crook2018年08月23日 10:39:28 +00:00Commented Aug 23, 2018 at 10:39