IE lose focus after field has been clicked into - javascript

I have an error layer that is presented on a form for an invalid/blank entries. When that error layer is presented, I want the current field to lose focus. In IE, I can't get this to work. The focus is always remaining in the field.
<!--Jquery function to override JS alert with DOM layer alert message-->
function customAlert(){
var args = arguments;
if(args.length > 1) {
// check that custom alert was called with at least two arguments
var msg = args[0];
$("li").removeClass("alertRed");
$("input").removeClass("CO_form_alert");
$("select").removeClass("CO_form_alert");
var div = $(".errorPopup");
div.css({"display":"block"});
if (div.length == 0) {
div = $("<div class='errorPopup' onclick='$(this).hide();'></div>");
$("body").prepend(div);
}
div.html(msg);
for(var i = 1; i < args.length; i++) {
var inputID = args[i];
$("#"+inputID).addClass("CO_form_alert").parent().addClass("alertRed");
$("input,select,radio,checkbox").focus(function(){
$(this).unbind('focus'); // remove this handler
$('.errorPopup').hide(); // hide error popup
});
}
}
}
I've tried ('body').focus(); and $("#"+inputID).focusout(); which also don't work.
I also tried:
div.css({"display":"block"});
$("input,select,radio,checkbox").blur();
and
$("input,select,radio,checkbox").blur(function(){
$(this).unbind('focus'); // remove this handler
$('.errorPopup').hide(); // hide error popup
});
but neither one works.

Use blur method.
$("input,select,radio,checkbox").blur();

Did you try
$("input,select,radio,checkbox").blur();
?

Related

What is this piece of Javascript for Isotope filter doing?

I am having some trouble understanding what is happening in a piece of vanilla JS for the Isotope filter. The original code is here: https://codepen.io/desandro/pen/VWLJEb
var buttonGroups = document.querySelectorAll('.button-group');
for (var i = 0; i < buttonGroups.length; i++) {
var buttonGroup = buttonGroups[i];
var onButtonGroupClick = getOnButtonGroupClick(buttonGroup);
buttonGroup.addEventListener('click', onButtonGroupClick);
}
function getOnButtonGroupClick(buttonGroup) {
return function(event) {
// check for only button clicks
var isButton = event.target.classList.contains('button');
if (!isButton) {
return;
}
var checkedButton = buttonGroup.querySelector('.is-checked');
checkedButton.classList.remove('is-checked')
event.target.classList.add('is-checked');
}
}
What is happening between the getOnButtonGroupClick function and it being assigned to a variable in the for loop preceding it?
getButtonGroupClick returns a closure that saves the value of buttonGroup. When you click on a button in the button group, it uses that closure variable to search for the checked button in the group, uncheck it, and then check the button you clicked on.
This complexity isn't really needed. When an event listener is called, event.currentTarget is set to the element that the listener was attached to, so you could just use that.
var buttonGroups = document.querySelectorAll('.button-group');
for (var i = 0; i < buttonGroups.length; i++) {
var buttonGroup = buttonGroups[i];
buttonGroup.addEventListener('click', onButtonGroupClick);
}
function OnButtonGroupClick(event) {
// check for only button clicks
var isButton = event.target.classList.contains('button');
if (!isButton) {
return;
}
var checkedButton = event.currentTarget.querySelector('.is-checked');
checkedButton.classList.remove('is-checked')
event.target.classList.add('is-checked');
}
The for loop is used to iterate over all of the elements with the class of button-group and and a click event listener to them. getOnButtonGroupClick returns a function to be used as the function to be used as the event listener for the element i.e. the function that is run when the element is clicked on.
var buttonGroups = document.querySelectorAll('.button-group');
//get all elements within the document with a class of button-group
//buttonGroups is a NodeList
for (var i = 0; i < buttonGroups.length; i++) {
//loop through all of the elements with a class of button-group matched by the above query selector
var buttonGroup = buttonGroups[i];
//get the element in the NodeList with the index i
var onButtonGroupClick = getOnButtonGroupClick(buttonGroup);
//get the function to be run when the element is clicked on
buttonGroup.addEventListener('click', onButtonGroupClick);
//add a click event listener to the element
}
function getOnButtonGroupClick(buttonGroup) {
return function(event) {
// check for only button clicks
var isButton = event.target.classList.contains('button');
//check if the element has a class of button
if (!isButton) {
//if the element does not have a class of button, do nothing
return;
}
var checkedButton = buttonGroup.querySelector('.is-checked');
checkedButton.classList.remove('is-checked')
event.target.classList.add('is-checked');
}
}
If I understood your question correctly, It means that a click event is being added to every button in the buttonGroups there is. Although, if you ask me, it would be way better and cleaner to just use a forEach, like so:
const buttonGroups = document.querySelectorAll('.button-group');
buttonGroups.forEach(button => button.addEventListener("click", OnButtonGroupClick)
function OnButtonGroupClick(event) {
// check for only button clicks
let isButton = event.target.classList.contains('button');
if (!isButton) {
return;
}
let checkedButton = event.currentTarget.querySelector('.is-checked');
checkedButton.classList.remove('is-checked')
event.target.classList.add('is-checked');
}
So, you add a click event to ALL the buttons in the buttonGroups that will run the function onButtonGroupClick.
EDIT: And there's no really need to assign the function like that... at all. Just call it on the click event and that's it.

Javascript remove click event with element removal [duplicate]

This question already has answers here:
Javascript removeEventListener not working
(13 answers)
Closed 6 years ago.
I have 1 div (a message) which appears on the page when the page is loaded. When a user clicks somewhere on a page outside this message I want this message to disappear and show (ONCE) a log in the console that the message has disappeared. The problem is I continue receiving my console messages every time I click everywhere on my page though the message is already gone. I.E. I cannot detach 'click' event from my page. The code is following:
var elems = document.querySelectorAll(':not(#my-widget)'); //all elements in my page except message
var promptwidget = document.getElementById('my-widget');
console.log('WIDGET==> ' + promptwidget);
if (typeof(promptwidget) != 'undefined' && promptwidget != 'null') {
for (var i = 0; i < elems.length; i++) //add click eventlistener to the rest document
{
elems[i].addEventListener("click", function(e) {
e.preventDefault(),
removeWidget(["my-widget"]), //parentNode.removeChild wrapper, works OK
console.log('widget removed'), //received everytime I click on a page but I need only ONCE
promptwidget = document.getElementById('my-widget'); //tried to reassign a null value to my promptwidget var and call removeEventListener but no work
});
}
} else //this code never called, but I want it after my-widget removal
{
for (var i = 0; i < elems.length; i++) {
elems[i].removeEventListener("click", function(e) {
e.preventDefault(),
console.log("clickevent removed")
});
}
}
Any help would be appreciated.
EDIT_1:
Thank you everyone, the problem was solved as follows:
var elems = document.querySelectorAll(':not(#my-widget)');
var promptwidget = document.getElementById('my-widget');
for(var i = 0; i<elems.length; i++)
{
elems[i].addEventListener("click", function(e)
{
e.preventDefault();
if(typeof(promptwidget) != 'undefined' && promptwidget != null)
{
removeWidget(["my-widget"]),
console.log('widget removed'), //now showed once
promptwidget = undefined
}
});
}
This code was very helpful
addEventListener allows you to specify more than one event handler for each event type, so to remove a specific event handler you need to specify not only the event type, but also which handler you want to remove:
addEventListener(eventType, eventHandler);
removeEventListener(eventType, eventHandler);
// arguments passed to removeEventListener must be exactly the same
// as in addEventListener so you cannot pass an anonymous function
It doesn't make sense to pass a newly declared anonymous function as the 2nd parameter to removeEventListener. You need to pass a reference to the actual function to be removed. You will have to define this function with a name outside of the scope, and then you can use the name as a reference to remove it.
function removeWidgetFn (e) {
e.preventDefault(),
removeWidget(["my-widget"]),
console.log('widget removed'),
promptwidget = document.getElementById('my-widget');
});
And then,
elems[i].addEventListener("click", removeWidgetFn);
And then,
elems[i].removeEventListener("click", removeWidgetFn);
An element can have many click handlers, so you need to specify which click handler you want to remove.

Call script from another script

In HTML5 I have a dropdown menu . When choosing different options I hide or show different parts of my page. Here is that script:
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
However what I want to do now, in another script is to preload an option from the dropdown. I can do it easily with this script:
setSelectedIndex(document.getElementById('target'),'content_1');
function setSelectedIndex(s, valsearch)
{
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++)
{
if (s.options[i].value == valsearch)
{
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
return;
}
This is where my problem comes up, my dropdow will get the value I want, but the part that I want to be shown when choosing that option won't come up.
That is because change events need to happen from the browser.
When the user commits the change explicitly (e.g. by selecting a value
from a 's dropdown with a mouse click, by selecting a date
from a date picker for , by selecting a file in the
file picker for , etc.);
If your using Jquery you can:
$("#id").val("value").trigger('change');
or you can use javascript if your not worried about building the event object:
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
else
element.fireEvent("onchange");
I would recommend moving your anonymous onchange function into a named function that you can call once onload, and again onchange.
Here is the function I wrote:
function setContent(id) {
//get the current visible content
var vis = document.querySelector('.vis');
//get the target element by id
var target = document.getElementById(id);
//make current vis element inv
if (vis) vis.className = "inv";
//make target element vis
if (target) target.className = 'vis';
}
and a fiddle
edited: got rid of querySelectorAll to stick closer to OP original code and updated fiddle. clarified and commented code.
The problem you have is changing a vale or the selected value of an input with JavaScript does not trigger any change event. So you would need to manually trigger the event.
function setSelectedIndex(s, valsearch)
{
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++)
{
if (s.options[i].value == valsearch)
{
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
//Setting the selected value with JavaScript does not trigger the change event so you need to manually trigger the change event
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
s.dispatchEvent(evt);
} else {
s.fireEvent("onchange");
}
return;
}

IE click event span not triggered

I'm having this webpage
http://pocolocoadventures.be/reizen/
And it should filter (with isotope.js) the travelboxes on the page.It does in safari, chrome, firefox, opera, .. but in IE, the filter doesn't work. Even worse, JS doesn't react at all at a click event on te span.
This is the piece of js
// Travel Isotope
var container = $('#travel-wrap');
container.isotope({
animationEngine : 'best-available',
itemSelector: '.travel-box ',
animationOptions : {
duration : 200,
queue : false
},
});
$(".filters span").click(function(){
var elfilters = $(this).parents().eq(1);
if( (elfilters.attr("id") == "alleReizen") && elfilters.hasClass("non-active") )
{
$(".label").each(function(){
inActive( $(this) );
});
setActive(elfilters);
}
else{
//set label alleReizen inactive
inActive( $("#alleReizen") );
if( elfilters.hasClass("non-active") ){
setActive(elfilters);
}
else{
inActive(elfilters);
}
}
checkFilter();
var filters=[];
$(".search.filters").children().each(function(){
var filter = $(this).children().children().attr("data-filter");
if( $(this).hasClass("non-active") ){
filters = jQuery.grep(filters, function(value){
return value != filter;
});
}
else{
if(jQuery.inArray(filter,filters) == -1){
filters.push(filter);
}
}
});
filters = filters.join("");
filterItems(filters);
});
function filterItems(filters){
console.log("filter items with filters:" + filters);
container.isotope({
filter : filters,
}, function noResultsCheck(){
var numItems = $('.travel-box:not(.isotope-hidden)').length;
if (numItems == 0) {
$("#no-results").fadeIn();
$("#no-results").css("display", "block");
}
else{
$("#no-results").fadeOut();
$("#no-results").css("display", "none");
}
});
}
function setActive(el){
el.removeClass("non-active");
var span = el.find('i');
span.removeClass("fa-check-circle-o").addClass("fa-ban");
}
function inActive(el){
el.addClass("non-active");
var span = el.find('i');
span.removeClass("fa-ban").addClass("fa-check-circle-o")
}
function checkFilter(){
var filterdivs = $('.filters span').parent().parent();
if( filterdivs.not('.non-active').length == 0 ){
setActive( $("#alleReizen") );
}
var filterLabels = $(".filters .label");
if( filterLabels.not('.non-active').length == 0){
setActive( $("#alleReizen") );
}
}
function noResultsCheck() {
var numItems = $('.item:not(.isotope-hidden)').length;
if (numItems == 0) {
//do something here, like turn on a div, or insert a msg with jQuery's .html() function
alert("There are no results");
}
}
Probably something small and stupid; but I can't find it..
Thanks in advance!
On your website you've build the buttons like this:
<button>
<span>
</span>
</button>
Now the button element is designed to be a button. It differs from the input button. In the latter you'd set the caption using value. In the button element you set it as a text node. The button element can contain elements like a span. The spec isn't very clear about whether or not you should have event handlers on the children of the button element. It's a browser developers interpretation of allowing it or not.
This problem has been posted here before (a few times)
span inside button, is not clickable in ff
Missing click event for <span> inside <button> element on firefox
It seems that Firefox is allowing it, based upon your findings. IE isn't. So to be on the safe side: use the button the way it was intended.
Wrap the button inside a span (not really logical)
Put the click handler on the button.
$(".filters button").click(...);
played around in the console a bit, and this seemed to work well.
$(".filters").on('click', 'span', function(){
// foo here
console.log('foo');
});
Maybe the filters are manipulated by one of your js files after page load?
.on will allow you to select a container which listens on changes that happen inside it, passing the element you want the actual action to work on.
If it's ok for you, I'd suggest to use the <button> element, instead of the <span>.
Let me know if that works for you.

Clear error message (jquery) on input field focus

function customAlert(inputID,msg){
var div = $(".errorPopup");
div.css({"display":"block"});
$("#"+inputID).addClass("CO_form_alert").parent().addClass("alertRed");
if (div.length == 0) {
div = $("<div class='ErrorPopup' onclick='$(this).hide();'></div>");
$("body").prepend(div);
}
div.html(msg)
}
I am using the above jquery to hijack my form's javascript validation and error handling. It's working well, except I need to clear the error messaging and styling once the user clicks back into the field to correct it.
EDIT:
based on answers below, got it working - but I need to remove the focus on the field for IE (it already does this in firefox) -
<!--Jquery function to override JS alert with DOM layer alert message-->
function customAlert(){
var args = arguments;
if(args.length > 1) {
// check that custom alert was called with at least two arguments
var msg = args[0];
$("li").removeClass("alertRed");
$("input").removeClass("CO_form_alert");
$("select").removeClass("CO_form_alert");
var div = $(".errorPopup");
div.css({"display":"block"});
if (div.length == 0) {
div = $("<div class='errorPopup' onclick='$(this).hide();'></div>");
$("body").prepend(div);
}
div.html(msg);
for(var i = 1; i < args.length; i++) {
var inputID = args[i];
$("#"+inputID).addClass("CO_form_alert").parent().addClass("alertRed");
$("#"+inputID).focus(function(){
$(this).unbind('focus'); // remove this handler
$('.errorPopup').hide(); // hide error popup
});
}
}
}
$(":input").keypress(function(event) {
$(".ErrorPopup").html("");
});
Hide the error popup div on the input's focus event:
$('#' + inputID).focus(function() { $('.ErrorPopup').hide(); });
Try this:
function customAlert(inputID,msg){
var div = $(".errorPopup");
div.css({"display":"block"});
$("#"+inputID).addClass("CO_form_alert").parent().addClass("alertRed");
if (div.length == 0) {
div = $("<div class='errorPopup' onclick='$(this).hide();'></div>");
$("body").prepend(div);
}
div.html(msg);
$("#"+inputID).focus(function(){
$(this).unbind('focus'); // remove this handler
$(this).removeClass("CO_form_alert")
.parent().removeClass("alertRed"); // undo changes
$('.errorPopup').hide(); // hide error popup
});
}

Categories