I am encountering a weird problem here, I have a div having an click event attached to it, and a input having on-blur event and button having click event attached to it.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div onClick='div()'>
<input onBlur='input()' />
<button onClick='button(event)'> ABCD </button>
</div>
</body>
</html>
Here are the functions that gets called when buttons are clicked.
function input(event){
console.log('input')
event.stopPropagation();
}
function button(event) {
console.log('button')
event.stopPropagation();
}
function div(){
console.log('div')
}
The problem that I am encountering here is that, if I click inside the input box then it is logging what is inside the div function, I tried event.stopPropagation(), but it doesn't seem to work is there any way to make it work? i.e - not logging what is inside div on clicking the input.
Here is a Bin for the same.
You have to set stop propagation for input click not on blur ,
so the div click will not be propagated :
see below snippet
function input(){
console.log('input')
event.stopPropagation();
}
function inputStopPropagation() {
event.stopPropagation();
}
function button(event) {
console.log('button')
event.stopPropagation();
}
function div(){
event.stopPropagation();
console.log('div')
}
<div onClick='div()' style="padding:5px; background :green">
<input onBlur='input()' onClick='inputStopPropagation()' />
<button onClick='button(event)'> ABCD </button>
</div>
Related
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pew Pew</title>
</head>
<body>
<canvas id="gameCanvas" height="800px" width="1000px"></canvas>
<div class="button-div">
<button id="atkUp" onclick="player.attackSpeedUp()">1 Atk Speed - 1c</button>
<button id="dmgUp" onclick="player.damageUp()">1 Damage - 1c</button>
<button id="multishotUp" onClick="player.multishotUp()">1 Multi-Shot - 1c</button>
<button id="moveSpeedUp" onClick="player.moveSpeedUp()">1 Move Speed - 1c</button>
<button id="armorUp" onclick="player.armorUp()">1 Armor - 1c</button>
<p>UPGRADES</p>
</div>
</body>
</html>
document.addEventListener("keypress", (event) =>{
if(event.keyCode == 32){
player.shoot();
}
}, false);
My problem is that when I click on any of my upgrade buttons (any button within .button-div), when I press the space key it activates ('clicks') the last button I pressed and does NOT fire my eventlistener. Is there a way to programmatically un-focus the most recent button and/or stop the button from robbing me of my space bar input.
Try this, the problem was that when you click a button you focus on this button, and the space bar triggers a trick on the button that yout are focused. I added some code to remove focus, to blur all buttons when you press the spacebar:
function deselectAllUpgradeButtons() {
for (const element of document.querySelector('.button-div').children) {
element.blur();
}
}
document.addEventListener(
'keypress',
(event) => {
if (event.keyCode == 32) {
deselectAllUpgradeButtons();
player.shoot();
}
},
false
);
Try this:
document.body.onkeyup = function(event){
event.preventDefault()
if(event.keyCode === 32){
player.shoot();
}
};
I am writing a function that should change the color of an h1 tag based on the value of the text in a text input form field. My HTML and JavaScript code is below:
function checkIfZero() {
//Get relevant elements from dom.
let value = parseInt(document.getElementById('text-field'));
let heading = document.getElementById('heading');
//Check if the element is zero, if so, adjust the color of the H1
if (value === 0) {
heading.style.color = 'green';
} else {
heading.style.color = 'red';
}
}
//Bind the function to onsubmit.
let form = document.getElementById('my-form');
form.onsubmit = function() {
checkIfZero();
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src='throwaway.js' type='text/javascript' defer></script>
<h1 id='heading'>This is a heading</h1>
<form id='my-form'>
<input type='text' id='text-field'>
<input type='submit' id='submit'>
</form>
</body>
</html>
Here, if I type in the number 0 in my input field and press enter (or click Submit), the color of the h1 tag does not change. However, I did check if the event was triggered or not.
When I amend my event listener to this:
let form = document.getElementById('my-form');
form.onsubmit = function() {
alert('You submitted the form');
};
, the alert does pop up in the browser. This suggests that there is an issue with my checkIfZero() function and not necessarily binding the function to the form element.
May I know how to fix my function so that it does change color upon firing the submit event? Thank you.
On blur of an input field I want to run a validator. If validation fails I need to set focus back in to the field and cancel out the next intended operation.
I am able to achieve the first part, to set the focus back into the field, but the next operations (button click, link click) are also executing. I need help in restricting actions if validation fails in blur.
Following is the code snippet replicating this behavior. Focus on the field and then try to click on the link/button. Their callbacks are getting executed, which I need to restricted if there is an error on blur event handler of the input field.
$(document).ready(function() {
$('.form-control').blur(function(e) {
var $this = jQuery(this),
hasError = true;
if (hasError) {
setTimeout(function() {
$this.focus();
}, 0);
return false;
}
});
$('.link').click(function(e) {
console.log('link clicked');
});
$('.button').click(function(e) {
console.log('button clicked');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type="text" class="form-control" />
<br/><br/>
Link
<br/><br/>
<button class="button">Submit</button>
</div>
You can try with pointer-events
$(document).ready(function() {
$('.form-control').blur(function(e) {
var $this = jQuery(this),
hasError = $this.val().trim()== ''?true:false;
if(hasError) {
setTimeout(function() {
$this.focus();
}, 0);
$('.link, .button').css('pointer-events','none');
}
else $('.link, .button').css('pointer-events','');
});
$('.link').click(function(e) {
console.log('link clicked');
});
$('.button').click(function(e) {
console.log('button clicked');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div class="container">
<input type="text" class="form-control" />
<br/><br/>
Link
<br/><br/>
<button class="button"> Submit</button>
</div>
</body>
</html>
I'm trying to invoke a JavaScript function (that have some php code ) when clicking a button..
but the function doesn't work in first time!! I should click two times to make it start.
here is my code...
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
function f1(id)
{
document.getElementById("hiddenVal").value = id;
window.alert("the function is started");
window.alert(id);
f2();
}
function f2()
{
<?php
$Biid=$_POST["hiddenVal1"];
?>
window.alert("<?php echo $Biid; ?>");
}
</script>
</head>
<body>
<form method="post">
<button id="2" onclick="f1(this.id)"> click me </button>
<input type="text" name="hiddenVal1" id="hiddenVal" /> </div>
</form>
</body>
</html>
the problem is that the default behavior of a button inside a form is to submit that form
So you can add a type attribute to the button so it won't submit the form or use a event listener with a "preventDefault" function just like this:
Option 1:
<button id="2" type="button" onclick="f1(this.id)"> click me </button>
Option 2:
document.addEventListener('submit', function(event){
event.preventDefault();
f1(event.target.id);
});
Looking at the MagicSuggest examples, when you click in the component or tab into the component the component's style changes (blue border around the component and the keyboard cursor is in the input field). How do you programmatically give focus to the MagicSuggest component?
I've tried $(...).focus() but this does not provide the same behavior. Some debugging points me to needing to trigger the _onInputFocus event handler, but I can't get this to fire programmatically. Using $(...).find('input[id^="ms-input"]').focus() gives focus to the internal input field, but does not do so in the same manner as user interaction (the component does not have the blue border and the keyboard cursor is after the Type or click here "empty text").
The following example demonstrates trying to programmatically put focus on the MagicSuggest component. Click on the OK button will clear the MagicSuggest selection and should put focus on the MagicSuggest component.
Am I doing something wrong or is this a limitation of MagicSuggest? If the latter, what would be the best way to correct it?
example.html:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>MagicSuggest Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
<form id="frm-ms" method="post" action="">
<p>
<label id="lbl-ms" for="ms-ex">MagicSuggest Example:</label>
<div id="ms-ex"></div>
</p>
<p>
<button id="btn-ok" type="button">OK</button>
</p>
<input id="ms-data" type="hidden" disabled />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- http://raw.github.com/nicolasbize/magicsuggest/master/src/magicsuggest-1.3.1.js -->
<script type="text/javascript" src="magicsuggest-1.3.1.js"></script>
<!-- http://raw.github.com/nicolasbize/magicsuggest/master/src/magicsuggest-1.3.1.css -->
<link rel="stylesheet" type="text/css" href="magicsuggest-1.3.1.css" />
<script type="text/javascript" src="example.js"></script>
</body>
</html>
example.js:
var msex = (function () {
'use strict';
var _handlers, init;
_handlers = {
_okClick: function () {
var $msex, msexMS, msg;
console.group('_okClick');
msg = 'OK button clicked.';
console.log('msg=' + msg);
$msex = $('#ms-ex');
console.log('$msex=');
console.dir($msex);
msexMS = $msex.magicSuggest();
console.log('msexMS=');
console.dir(msexMS);
// Make MS process raw value.
$msex.blur();
msexMS.clear();
// TODO: Figure out how to get the appropriate focus in MagicSuggest, with the blue border and the cursor in the input field.
console.log('MS focusing ...');
$msex.find('input[id^="ms-input"]').focus();
console.log('MS focused.');
console.groupEnd();
}
};
init = function () {
var msData, $msex, msexMS;
console.group('init');
msData = [
{id:'001', description:'ABC (001)'},
{id:'002', description:'DEF (002)'}
];
console.log('msData=');
console.dir(msData);
$('#ms-data').val(JSON.stringify(msData));
$msex = $('#ms-ex');
msexMS = $msex.magicSuggest({
allowFreeEntries: true,
allowValueEntries: true,
displayField: 'description',
valueField: 'id',
data: msData,
maxDropHeight: 145,
toggleOnClick: false,
name: 'code',
maxSelection: 1,
value: ['001'],
width: 200
});
$('#btn-ok').click(_handlers._okClick);
console.groupEnd();
};
return {
init: init
};
})();
$(document).ready(function () {
'use strict';
msex.init();
});
Try this
if (msControl != undefined)
{
msControl.input.focus();
}
Debugging through the example showed that after processing the OK button click handler, the MagicSuggest component was being blurred by a bubbled click event.
A working solution is to add event.stopPropagation() to the OK button click handler, trigger blur on the MagicSuggest component and trigger focus on the MagicSuggest component input field.
$msex.blur(); // Process raw value.
$msex.find('input[id^="ms-input"]').focus();