Initiate click on div using tab and enter - javascript

I have a and div element
link
<div tabindex="0">div</div>
And click event handlers
$("a").on("click",function(){
alert(" a click")
});
$("div").on("click",function(){
alert("div click")
});
Using keyboard tab I can navigate to a link ,press Enter and see alert,but I can't do this for div.
Is it possible initiate click event for div as same as for a tag,without using any other events(keypress)?
JSfiddle

You can create a custom event like this:
$("div").on("click enter",function(){
alert("div click")
})
.on('keypress', function(e) {
if(e.which === 13) {
$(this).trigger( 'enter' );
}
});
DEMO

I know this is an old post but i thought i might add something.
PeterKA has a nice solution but i would improve it just a bit.
Instead of triggering a new custom event like enter just trigger the click event. This way you don't need to modify existing code and add the new event to every listener you have.
Each element that listens to click will be triggered.
$('.btn').on("click",function(){
alert("div click")
})
// at a centrelized spot in your app
$('.btn').on('keypress', function(e) {
if(e.which === 13) {
$(this).trigger('click');
}
});
$(document).ready(function(){
$('#firstDiv').focus(); // just focusing the first div
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="firstDiv" class="btn" tabindex="0">div</div>
<div class="btn" tabindex="0">div</div>
<div class="btn" tabindex="0">div</div>

Related

Detect input button down state

How can I detect if the button below is currently pressed down (being held down)?
<input type="button" value="Hold it down" id="aButton">
To clarify, I don't mean to detect if the button is clicked, but being held down in the active state.
I tried to use the mousedown event but it doesn't work if the user operates the button with the keyboard, tabbing to the button and holding the space bar down.
It work fine with jquery mousedown (onmousedown in native js ) mouseup (onmouseup in native js ) events , bellow the working sample :
$(document).ready(function(){
$("#btn").on("mousedown",function(){
console.log("btn click down using mouse");
})
var firstKeydown = true;
$("#btn").on("keydown",function(e){
if(e.which == 32){ // check if clicked button is sapcebar "code =32"
if(firstKeydown) { // to prevent multiple firing
console.log("btn click down using keyboard");
firstKeydown = false;
}
}
})
$("#btn").on("mouseup",function(){
console.log("btn click up using mouse");
})
$("#btn").on("keyup",function(e){
if(e.which == 32) { // check if clicked button is sapcebar "code =32"
console.log("btn click up using keyboard");
firstKeydown =true;
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Button</button>

Click Node Without Clicking Parent Node

I have a <button> that is wrapped inside of a <div>. I want to be able to click the button without actually clicking on the <div> as well. The <button> needs to remain inside of the <div>.
Heres the code:
<div onclick='console.log("Div was clicked.")'>
This is the Div
<button onclick='console.log("Button was clicked.")'>Button</button>
</div>
When i click on the <div> console logs "Div was clicked.".
When i click on the <button> console logs "Button was clicked." AND "Div was clicked.".
How can i click on the <button> WITHOUT a click registering on the <div>?
Any alternatives/workarounds?
Thanks guys.
Add event.stopPropagation() in your button onclick handler.
<div onclick='console.log("Div was clicked.")'>
This is the Div
<button onclick='event.stopPropagation(); console.log("Button was clicked.")'>Button</button>
</div>
You can also check the target.id. Here's a small example using jQuery:
HTML:
<div id="parent">
This is the Div
<button onclick='console.log("Button was clicked.")'>Button</button>
</div>
jQuery:
$('#parent').click(function(e)
{
if (e.target.id == "parent") {console.log("Div was clicked.")}
});
Fiddle: http://jsfiddle.net/mrnLLvac/
Add the following JavaScript function:
function CancelMouseEvent (Event)
{
Event = Event ? Event : window.Event;
if (Event.stopPropagation) { Event.stopPropagation(); }
if (Event.preventDefault) { Event.preventDefault(); }
Event.cancelBubble = true;
Event.cancel = true;
Event.returnValue = false;
return false;
}
Now use this in HTML:
<button onclick='console.log("Button was clicked."); CancelMouseEvent(event);'>Button</button>
Usually, it is recommended to not use the older method of event binding to HTML. It is recommended to use addEventListener, that way your JS stays in your JS and your HTML is only HTML.
A simple example below:
<div id="wrap">
This is the Div
<button id="button">Button</button>
</div>
<script>
var wrap = document.getElementById('wrap');
wrap.addEventListener('click', handleClick, true);
function handleClick(e) {
e.stopPropagation;
if (e.target.id === 'button') {
// do stuff because button was clicked
console.log('button was clicked');
}
}
</script>
EDIT: why your code didnt work
Your code didn't work because events "bubble" up the DOM (they can also be "captured"...), in your case even if you clicked "button", the following events were triggered:
Button (target) === (bubbling up to its parent) === DIV (its event was also triggered).

Keyup event in focused input when clicked link

I have a button and when it have clicked I show some input field.
The input field tracks keyup events itself.
When I click the button using my keyboard (focus it then hit return) the input field receives an unexpected keyup event.
Demo: http://jsfiddle.net/LpXGM/3/ (just hit return and look at the messages on the page)
But if I add a timeout everything works as expected. Demo: http://jsfiddle.net/8BRmK/1/ (no keyup event when hitting return on the button)
Why does this strange thing happen? And how can I fix it?
The code with the handlers:
$button.on("click", function(){
showModal();
});
$emailField.on("keyup", function(event) {
// process the event
});
var showModal = function() {
$modal.show();
$emailField.focus();
}
Possible solution without timeOut: http://jsfiddle.net/agudulin/3axBA/
$button.on("keypress", function(event){
if (event.keyCode == 13) {
return false;
}
});
$button.on("keyup", function(event){
if (event.keyCode == 13) {
showModal();
$status.append($("<span>enter has been pressed</span></br>"));
}
});
Try $button.on("keyup mouseup", function(){
or $emailField.on("keypress", function(event) {
try
$(document).ready(function(){
$(document).on("click",".btn",function(e){
$status.append($("<span>btn click</span></br>"));
});
$(document).on("keyup",".email",function(e){
$status.append($("<span>keyup " + event.keyCode + "</span></br>"));
});
});
yes its happens because one you click the keyboard than the button click event fire first and than as per your logic your input field take focus and your keyup event is fire. but when you give Timeout so click event is fire first but because of timeout your logic is delayed and than your your keyup event done our work so the focus in not in your input that why it not enter any word in your input.

Javascript shows ids of both body and clicked elemnt on click event

I have one js function,say check(val). I call it on click event on body and one tag. When I click on body it correctly shows id of body element. But,when when I click on , it shows ids of both and body!
I just want to display id of on click and on body's click event some other action to be executed.
My sample HTML code:
<body id="body" onclick="check(this.id);">
<a href="#" id="ele" onclick="check(this.id)">Hello</div>
</body>
JS Code :
function check(val)
{
if(val=="ele"){
alert("element is clicked");
}else if(val=="body"){
alert("Body is clicked");
}
}
you need to stop Propagation of event using event.stopPropagation() method. already #StephenThomas mentioned this in comment of your question.
try this,
HTML markup:
<body id="body" onclick="check(event,this.id);">
<a href="#" id="ele" onclick="check(event,this.id)">Hello</div>
</body>
javascript code:
function check(event, val) {
if (val == "ele") {
alert("element is clicked");
event.stopPropagation(); //here we stop propagation of the event
} else if (val == "body") {
alert("Body is clicked");
}
}
SEE THIS DEMO.
I hope this would help you...
Every browser handles event bubbling differently. Some will show both and some will only show the link. You can change the function to fit every clicked element:
function check(val)
{
alert("Clicked element type is: " + val.nodeName);
}
This way you don't need any id detection because you check the type of the node itself.
You are getting both ids because when you click on the anchor you are also clicking on the body since the anchor is a child of the body element.
important note:when you click on the anchor you are also clicking on the body
use like this
<body id="body" onclick="check(this);">
Hello
</body>
Javascript
function check(val)
{
if(val.id.toString()=="ele"){
alert("element is clicked");
}else if(val.id.toString()=="body"){
alert("Body is clicked");
}
}

html div onclick event

I have one html div on my jsp page, on that i have put one anchor tag, please find code below for that,
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint"
onclick="markActiveLink(this);">ABC</a>
</h2>
</div>
js code
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
here I when I click on div I got alert with 123 message, its fine but when I click on ABC I want message I want to call markActiveLink method.
JSFiddle
what is wrong with my code? please help me out.
The problem was that clicking the anchor still triggered a click in your <div>. That's called "event bubbling".
In fact, there are multiple solutions:
Checking in the DIV click event handler whether the actual target element was the anchor
→ jsFiddle
$('.expandable-panel-heading').click(function (evt) {
if (evt.target.tagName != "A") {
alert('123');
}
// Also possible if conditions:
// - evt.target.id != "ancherComplaint"
// - !$(evt.target).is("#ancherComplaint")
});
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
Stopping the event propagation from the anchor click listener
→ jsFiddle
$("#ancherComplaint").click(function (evt) {
evt.stopPropagation();
alert($(this).attr("id"));
});
As you may have noticed, I have removed the following selector part from my examples:
:not(#ancherComplaint)
This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.
I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.
Try this
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').click(function (event) {
alert($(this).attr("id"));
event.stopPropagation()
})
DEMO
Try following :
$('.expandable-panel-heading').click(function (e) {
if(e.target.nodeName == 'A'){
markActiveLink(e.target)
return;
}else{
alert('123');
}
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
Here is the working demo : http://jsfiddle.net/JVrNc/4/
Change your jQuery code with this. It will alert the id of the a.
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
markActiveLink();
alert('123');
});
function markActiveLink(el) {
var el = $('a').attr("id")
alert(el);
}
Demo
You need to read up on event bubbling and for sure remove inline event handling if you have jQuery anyway
Test the click on the div and examine the target
Live Demo
$(".expandable-panel-heading").on("click",function (e) {
if (e.target.id =="ancherComplaint") { // or test the tag
e.preventDefault(); // or e.stopPropagation()
markActiveLink(e.target);
}
else alert('123');
});
function markActiveLink(el) {
alert(el.id);
}
I would have used stopPropagation like this:
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
$('#ancherComplaint').on('click',function(e){
e.stopPropagation();
alert('hiiiiiiiiii');
});
Try out this example, the onclick is still called from your HTML, and event bubbling is stopped.
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint" onclick="markActiveLink(this);event.stopPropagation();">ABC</a>
</h2>
</div>
http://jsfiddle.net/NXML7/1/
put your jquery function inside ready function for call click event:
$(document).ready(function() {
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
});
when click on div alert key
$(document).delegate(".searchbtn", "click", function() {
var key=$.trim($('#txtkey').val());
alert(key);
});

Categories

Resources